Jezor Jezor - 21 days ago 4
C++ Question

Is there a way to prevent automatic variable from deletion?

I know it is the really bad thing to even think about and just for the record: I'm not trying to use it in any serious application, so please try to answer the question instead of pointing out how inappropriate it is.




Example of what I'm trying to accomplish:

class Example {
public:
Example() {
std::cout << "constructor called" << std::endl;
}

~Example() {
std::cout << "destructor called" << std::endl;
}

// some operator delete magic perhaps?
};

int main() {
Example* example_pointer;

{
Example example; // prints "constructor called"
example_pointer = &example;
} // example still exists here, nothing is printed

delete example_pointer; // deleting automatic variable manually
// Prints "destructor called"

return 0;
}


EDIT: The only requirement is that main function should not change.

I realize that some things are simply not possible, so I won't cry if that's the case here. This question came to my mind only out of curiosity.

Answer

Don't try this at home but you could probably achieve something like this using a reference counted PIMPL and an overloaded operator&:

class ExampleImpl {
public:
    ExampleImpl() {
        std::cout << "constructor called" << std::endl;
    }
    ~ExampleImpl() {
        std::cout << "destructor called" << std::endl;
    }
};

class Example {
    std::shared_ptr<ExampleImpl> impl;
public:
    Example() : impl(std::make_shared<ExampleImpl>()){}
    Example* operator&() { return new Example(*this); }
};

Live demo.

Comments