Question

In C++, is it safe to extend scope via a reference?

In code, what I mean is:

MyCLass& function badIdea()
{
    MyClass obj1;
    ...
    return obj1;
}
Was it helpful?

Solution

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

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top