C ++静态初始化顺序惨败 [英] c++ static initialization order fiasco
问题描述
我目前正在学习C ++,但遇到了一些麻烦.
I'm currently learning C++, and I'm having some troubles.
我已经通过使用许多 #define
开发了一个程序,但是我想改用 static const
(碰撞/类型/作用域...)
I've developped a program by using lots of #define
, but I'd like to use static const
instead (collision/type/scopes...).
所以,我现在有类似的东西:
So, I now have something like:
file1.hpp
class A {
public:
static const std::string MY_CONST_VAR;
};
file1.cpp
const std::string A::MY_CONST_VAR = "some string";
file2.cpp
static std::string arrayOfString[] = {
A::MY_CONST_VAR,
...
};
我的代码编译时没有警告/错误(使用-W -Wall -Wextra -Werror标志进行编译).
My code compiles with no warnings/errors (compiling with -W -Wall -Wextra -Werror flags).
但是,当我尝试运行它时,会导致段错误.
However, when I try to run it, it results in a segfault.
我已经用valgrind来运行它,它给了我以下输出:
I've ran it with valgrind, and it gave me the following ouput:
==11239== Invalid read of size 4
==11239== at 0x5F525CB: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.19)
==11239== by 0x40D076: _GLOBAL__sub_I__ZN16GraphicInterface13DEFAULT_WIDTHE (GraphicInterface.cpp:42)
==11239== by 0x51AC7C: __libc_csu_init (in /home/simon/PSU_2013_zappy/gui/gui_zappy)
==11239== by 0x66D8E54: (below main) (libc-start.c:246)
==11239== Address 0xfffffffffffffff8 is not stack'd, malloc'd or (recently) free'd
因此,segfault发生在arrayOfString实例化期间.我认为问题在于arrayOfInt在常量之前分配.但是在那种情况下,是否可以为此目的使用静态const?
So, the segfault occurs during the arrayOfString instanciation. I think the problem is that the arrayOfInt is allocated before the constant. But in that case, is it possible to use static const for this purpose?
我不知道如何解决此问题.我做错了吗?有更好的方法吗?如何解决这个问题?
I don't know how to patch this issue. Am I doing it wrong? Is there a better way to do it? How to solve this issue?
推荐答案
多亏了这些注释,我终于通过使用 constexpr
关键字解决了这个问题.
Thanks to the comments, I finally solved the problem by using constexpr
keyword.
它为我提供了以下工作代码:
It gives me the following working code:
file1.hpp
class A {
public:
static constexpr char MY_CONST_VAR[] = "some string";
};
file1.cpp
const char A::MY_CONST_VAR[];
file2.cpp
static std::string arrayOfString[] = {
A::MY_CONST_VAR,
...
};
这篇关于C ++静态初始化顺序惨败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!