【发布时间】:2021-09-08 09:42:49
【问题描述】:
我想在标头中有 const std::map 作为全局常量,将在其他 cpp-s 中使用。所以我将其声明为:
// header.h
const inline std::map<int, int> GlobalMap = { {1, 2}, {3, 4} };
但是,如果我在多个 cpp-s 中包含此标头,则会在退出时发生堆损坏,因为多个析构函数针对同一个内存地址运行。
我一直认为 inline const 是全局非文字常量的灵丹妙药。我已经将全局 std::string-s 声明为 const inline 并且它工作得很好。
所以我的问题是:
- 为什么会这样?这不是让
constinline 很容易出错吗? - 如何在 C++17 中正确声明全局
const std::map?以及如何确保只创建一个全局对象?
编辑: 我可以在 Visual Studio 2017 的以下项目中重现它(/std:c++17,Debug x86)
file_1.h:
#pragma once
#include <map>
const inline std::map<int, double> GlobalMap = {{1, 1.5}, {2, 2.5}, {3, 3.5}};
void f1();
file_1.cpp:
#include "file_1.h"
void f1()
{
(void)GlobalMap;
}
main.cpp:
#include "file_1.h"
int main()
{
f1();
return 0;
}
【问题讨论】:
-
这里只是猜测,但也许你忘了在顶部添加
#pragma once? -
@Gal 不,#pragma 曾经在顶部
-
@Gal 为什么会有不同?
-
您的解决方案应该没问题。问题出在其他地方。请提供一个复制案例。例如。您实际上可以在 wandbox 中创建多个文件:wandbox.org/permlink/rIFr1GkkKiJ1Ggzh
-
对我来说看起来像一个 Visual C++ 错误。它在最新的 2019 年运行良好,而 VS 2017 的 C++17 支持可能确实存在一些小故障。
标签: c++ constants c++17 inline stdmap