在基本析构函数中创建 self 的副本

Fel*_*ara 1 c++ inheritance

我想编写一个类家族,它们在被破坏时在某些条件下创建自身的副本。请看下面的代码

#include <string>
#include <iostream>

bool destruct = false;

class Base;
Base* copy;

class Base {
public:

virtual ~Base() {
    if (!destruct) {
        destruct = true;
        copy = nullptr; /* How to modify this line? */
        std::cout << "Copying" << std::endl;
    } else {
        std::cout << "Destructing" << std::endl;
    }
}

};

class Derived : public Base {
public:

Derived(const std::string& name) : name(name) {}

std::string name;

};

int main() {
    { Derived d("hello"); }

    std::cout << dynamic_cast<Derived*>(copy)->name << std::endl;

    delete copy;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我需要如何更改该行copy = nullptr;,使其执行完整复制this并且输出如下所示?

Copying
hello
Destructing
Run Code Online (Sandbox Code Playgroud)

Seb*_*edl 5

你不能。

当基析构函数运行时,派生析构函数已经运行并销毁了复制需要保留的信息。

你需要改变你的方法。