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.
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;
}
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); }
};