类的成员函数作为线程响应函数

在主线程启动线程1, 线程1中,创建A类型的实例,并且启动线程2。线程2的处理函数是类A的成员函数,当线程1退出的时候,会删除A的实例,但是这个时候线程2并没有结束,线程2仍然可以访问A实例的成员,只是成员的值已经是垃圾值,可是在线程1中已经删除了A的实例,A的析构也已经调用了。哪位同学给解释下是这怎么回事,A的实例到底被删除了吗?

#include 
#include 
#include 

class A
{
public:
    int num1;
    int num2;
    A(int value1,int value2):
     num1(value1),
     num2(value2)
    {
        std::cout << __FUNCTION__ << std::endl;
    }
    ~A()
    {
        std::cout << __FUNCTION__ << std::endl;
    }
    void startThead()
    {
        std::cout  << __FUNCTION__ << " start" << std::endl;
        std::thread t(&A::threadFunc,this);
        t.detach();
        std::cout  << __FUNCTION__ << " end" << std::endl;
    }
    void threadFunc()
    {
        std::cout << __FUNCTION__<<" start"<int index = 0;
        while (index < 50)
        {
            std::cout <<"index is " << index << ",and this is "<<this <<",and num is "<",and this->num address is"<<&(this->num2)<Sleep(1000); 
            index++;
        }
        std::cout << __FUNCTION__ << " end" << std::endl;
    }
};

void gthreadFunc()
{
    std::cout << __FUNCTION__ << " start" << std::endl;
    A* a = new A(5,20);
    a->startThead();
    printf("a address is %p,a->num2 address is %p\n", a,&(a->num2));

    getchar();
    delete a;
}
int main()
{
    std::thread gThread(gthreadFunc);
    gThread.detach();
    std::cout << "gThread created\n";
    while (true)
    {
        Sleep(1); 
    }
    std::cout << "main thread exit\n";
}

在上面的代码中,主线程创建了一个名为gThread的线程,并在gThread中创建了一个A类型的实例并且启动了一个线程,这个线程的处理函数是A类的成员函数threadFunc。在gThread线程中,在创建A实例之后立即调用了delete,删除了A的实例。

在这种情况下,A的实例的内存已经被释放,但是threadFunc线程仍然在运行并且访问A实例的成员num2。线程2访问A实例的成员并不会导致程序崩溃,因为访问A实例的成员并没有用到A实例本身。但是,因为A的实例已经被删除,所以num2的值是垃圾值,不能保证正确性。

这种情况下,主线程在调用delete之后,A实例就被删除了,但是线程2还在运行,并且访问了A实例的成员,这样就会产生不可预期的结果

望采纳

首先要理解,啥叫删除?怎么删除?
难道是biu的一声化为虚空????