Home > database >  Create copy of self in base destructor
Create copy of self in base destructor

Time:06-10

I want to write a family of classes that create copies of themselves under certain conditions when getting destructed. Please see the code below

#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;
}

How do I need to change the line copy = nullptr; such that it performs a full copy of this and the output becomes as shown below?

Copying
hello
Destructing

CodePudding user response:

You can't.

By the time the base destructor runs, the derived destructor has already run and destroyed information that the copying would need to preserve.

You need to change your approach.

  • Related