Reputation: 347416
In C++, is it safe to extend scope via a reference?
In code, what I mean is:
MyCLass& function badIdea()
{
MyClass obj1;
...
return obj1;
}
Upvotes: 10
Views: 5217
Reputation: 9764
It is NOT safe to extend the scope via reference. Objects in C++ are not reference counted when obj1 goes out of scope it will be deleted, refering to the result of badIdea() will only get you into trouble
Upvotes: 22
Reputation: 114765
The only place it's OK to extend a scope with a reference is with a const
reference in namespace
or function scope (not with class members).
const int & cir = 1+1; // OK to use cir = 2 after this line
This trick is used in Andrei Alexandrescu's very cool scope guard in order to capture a const
reference to a base class of the concrete scope guard.
Upvotes: 16
Reputation: 41106
Please clarify what you do mean.
Assuming you intend to do this:
int * p = NULL;
{
int y = 22;
p = &y;
}
*p = 77; // BOOM!
Then no, absolutely not, scope does not get extended by having a reference.
You may want to look at smart pointers, e.g. from boost libraries: clickety
Upvotes: 1