小编Smi*_*cer的帖子

C++调用过程中对象被销毁怎么办

这是我的测试代码

class bar
{
public:
    explicit bar(int x) : num(x) {}
    int get_num()
    {
        return num;
    }

private:
    int num;
};

shared_ptr<bar> ptr_store;

void get_func()
{
    while (1)
        printf("get_num:%d\n", ptr_store->get_num());
};

void set_func()
{
    while (1)
        //ptr_store = make_shared<bar>(1);
        atomic_exchange(&ptr_store, make_shared<bar>(1));

}

int main()
{
    ptr_store = make_shared<bar>(-1);
    std::thread t1(get_func);
    std::thread t2(set_func);
    t1.join();
    t2.join();
}
Run Code Online (Sandbox Code Playgroud)

我想知道为什么这个程序不会进行核心转储?

如果set_func在使用时t2破坏原点,是否会导致某些故障?是否由 保证?或者这只是一个巧合。ptr_storet1ptr_store->get_num()shared_ptr

Test environment:
OS: Ubuntu 20.04 LTS
Clang: clang version 3.9.1
G++: gcc version 7.5.0 …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading shared-ptr c++11 stdatomic

2
推荐指数
1
解决办法
117
查看次数

标签 统计

c++ ×1

c++11 ×1

multithreading ×1

shared-ptr ×1

stdatomic ×1