我想编写一个类家族,它们在被破坏时在某些条件下创建自身的副本。请看下面的代码
#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)