我有一个类,它有一些属性,如下所示,我的问题是当我在std::atomic<char*> atomic_input
之前删除或放置string s
属性时,程序会异常终止:
"标准::logic_error">
what((: basic_string::_M_construct 空无效
已中止(核心已转储(
#include <string>
#include <atomic>
// In ui.cpp
class UI
{
private:
std::atomic<char*> atomic_input;
std::string s; /* this can be renamed, but removing or placing it
before the above field crashes the program */
};
// In main.cpp
#include "ui.cpp"
int main()
{
srand (time(NULL));
initscr(); /* start the curses mode */
UI* ui = new UI();
return 0;
}
字符串属性不会以任何方式在程序中访问,可以重命名它。我有一个atomic
字段的原因是该值在多个线程之间共享。
我尝试将string
字段放在类属性中的不同行中,仅当声明在atomic_input
之前时,程序才会崩溃。
可能导致问题的原因是什么?这与如何定义C++中的类有关吗?
看起来我已经找到了解决方案。
std::atomic<char*> atomic_input
未初始化(如下所示(导致问题。我仍然不知道string
变量是如何干扰它的。
我的猜测是编译器以某种方式将string
解释为atomic_input
的构造函数。仅当在运行时而不是在编译中访问atomic_input
时,才会发生此错误。
#include <string>
#include <atomic>
// In ui.cpp
class UI
{
private:
std::atomic<char*> atomic_input{(char*)""};
// std::string s; /* Initializing the atomic char like above solved the problem */
};