C++多线程下子类"部分析构"问题

Posted unclerunning

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++多线程下子类"部分析构"问题相关的知识,希望对你有一定的参考价值。

C++多线程下子类”部分析构”问题

#include <string>
#include <iostream>

using namespace std;

/*
* This is a simple example used to reveal memory issue when we destruct a object of child class.
*1.Set two break points as shown below.
*2.Watch the memory of "ch".
*3.Start the exmple.
* Observe the memory content of "ch", we can get the following conclusions:
* When we break at ~child(), the memory of "ch" is still valid.
* The moment we break at ~Base(), the "child" memory part of "ch" becomes invalid but still the "base" memory 
* part is valid.

* Knowing this feature is especially important when we program under muti-thread.
*/
class Base

public:
    Base()
    
        name = "base object";
        cout << "Base()" << name << endl;
    

    ~Base() 
    
        // set a break point here.
        cout << "~Base() start " << name << endl;
    
    string name;
;

class child :public Base

public:
    child()
    
        cName = "child object";
        cout << "child()" << cName <<endl;
    
    ~child()
    
        // set a break point here.
        cout << "~child() start " << cName << endl;
    
    string cName;
;

child *ch = new child();

int main()

    delete ch;
    return 0;

reference

当析构函数遇到多线程──C++ 中线程安全的对象回调

Race condition in rtc::Thread::Clear()

Lifetime

Object Lifetime Manager A Complementary Pattern for Controlling Object Creation and Destruction

以上是关于C++多线程下子类"部分析构"问题的主要内容,如果未能解决你的问题,请参考以下文章

java多线程总结

c++中,析构函数和delete各有啥作用啊

C++编程经验(13):当析构函数遇上多线程

C++ 类的多态四(虚析构函数的重要性)

C++ 多线程 操作List 的问题

C++ 多线程std::thread 详解