使用成员函数的正在运行的线程期间销毁的对象

时间:2018-07-31 13:28:13

标签: c++ multithreading destructor

使用成员函数创建线程,但是相关对象到达作用域的末端并被销毁。我感到奇怪的是,线程继续运行而没有错误。我想这纯粹是运气,但我无法证明这一点。

#include <iostream>
#include <thread>
#include <chrono>

using namespace std::chrono_literals;
using namespace std;

struct Base {
    int N = 10;
    Base(int _N) : N(_N) {
        cout << "Base Ctor\n";
    }

    virtual ~Base(){
        cout << "Base Dtor\n";
    }

    void counter() {
        for ( auto i{0}; i < N; ++i ) {
            this_thread::sleep_for( 1s );
            cout << "step: " << i << " / " << N << endl;
        }
    }
};

int main() {
    {
        // limit the scope of b
        Base b(10);
        thread th( &Base::counter, std::ref(b) );
        th.detach();

        std::this_thread::sleep_for( 5s );
        // destruct b
    }
    std::this_thread::sleep_for( 10s );
    return 0;
}

我得到以下结果:

Base Ctor
step: 0 / 10
step: 1 / 10
step: 2 / 10
step: 3 / 10
Base Dtor
step: 4 / 10
step: 5 / 10
step: 6 / 10
step: 7 / 10
step: 8 / 10
step: 9 / 10

0 个答案:

没有答案