Will the following work, always?
class MyCLass {
int *pInt;
public:
MyCLass() {
pInt = new int;
*pInt = 42;
}
~MyCLass() {
delete pInt;
printf("Goodbye cruel world!");
}
void func1() {
printf("Hello World %d", *pInt);
}
};
MyCLass foo;
{
MyClass &bar = foo;
//Do stuff
}
foo.func1();
I am worried that in it’s mandate to exactly emulate the original object bar will cause invocation of the destructor as it goes out of scope.
No it won’t. The storage is entire related to foo in your example. When foo goes out of scope the destructor will get called.
Of course, if you still had a reference to that object the reference would be referencing a now non-existent object and that could give you issues.
Referencing does not emulate the original object. All it does is say that while that object is in existence then any call through the reference will be re-directed to that object.