C++删除未使用的类属性会导致 std::logic_error

C++ Removing Unused Class Attribute Causes std::logic_error

本文关键字:std logic error 未使用 删除 属性 C++      更新时间:2023-10-16

我有一个类,它有一些属性,如下所示,我的问题是当我在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 */
};