小编Bil*_*ang的帖子

在 std::thread 中运行时,C++ 成员变量的生命周期是多少?

#include <iostream>
#include <string>
#include <thread>

using namespace std;

struct safe_thread : public thread
{
    using thread::thread;

    safe_thread& operator=(safe_thread&&) = default;

    ~safe_thread()
    {
        if (joinable())
        {
            join();
        }
    }
};

struct s
{
    safe_thread t;
    std::string text = "for whatever reason, this text will get corrupted";

    s() noexcept
    {
        std::cout << text << '\n'; // it works in constructor as expected
        t = safe_thread{ [this]
                         { long_task(); }};
    }

    void long_task()
    {
        for (int i = 0; i < 500; …
Run Code Online (Sandbox Code Playgroud)

c++ lifetime c++11 stdthread

3
推荐指数
1
解决办法
137
查看次数

标签 统计

c++ ×1

c++11 ×1

lifetime ×1

stdthread ×1