10

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

In code, what I mean is:

MyCLass& function badIdea()
{
    MyClass obj1;
    ...
    return obj1;
}
Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636

3 Answers3

22

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

Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
Harald Scheirich
  • 9,676
  • 29
  • 53
  • The question was about C++ and reference binding. Reference counting does not enter into it. I've added an answer of my own, but briefly, you *can* extend the scope of an object by reference binding but should be careful in your design. Don't do it if you don't understand it. – Don Wakefield Nov 02 '08 at 17:13
  • I think he referred to reference counting since that is how you *could* return a reference without the local object going out of scope in languages that support reference counting (C++ not being one of them, of course). – Jim Buck Nov 02 '08 at 17:27
  • I can see how the term "reference counting" muddies the issues, i was trying to hint to mechanisms that other languages have that might keep allocated objects alive, maybe not a good idea – Harald Scheirich Nov 03 '08 at 13:18
16

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.

Motti
  • 110,860
  • 49
  • 189
  • 262
  • Note this is only "extending the scope" in the sense the the usually very narrow "scope" of a temporary is extended to the parent scope, which is quite different to what the OP was asking. Kudos for mentioning a little known aspect of C++ that a lot of people are confused by at first. – philsquared Nov 02 '08 at 14:33
1

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

peterchen
  • 40,917
  • 20
  • 104
  • 186