4

In the following code , I am initializing a reference variable with a literal.

class ABC { public: const int& a; ABC():a(43) { } void newfoo() { printf("NEWFOO %d",a); } }; int main() { ABC obj; obj.newfoo(); } 

The output of this program is NEWFOO 32767 which seems illogical when I know that the following code works just fine.

int main() { const int& b=3; printf("%d",b); } 

What is happening here ? If compiler declares some temp variable during initializing of the reference variable , then isn't the scope of that variable will be inside main since the class is in global scope ?

2
  • Don't initialize member references with literals. I believe it is undefined behavior. Commented Jan 31, 2014 at 13:41
  • 1
    Why was it standardized this way? It doesn't make sense to let this compile. Commented Jan 31, 2014 at 13:55

2 Answers 2

2

Well clang produces the following warning for this code even without any flags (see it live):

warning: binding reference member 'a' to a temporary value [-Wdangling-field] ABC():a(43) { } ^~ 

gcc on the other hand requires either -Wall or -Wextra.

and if we check out this reference initialization reference it says:

a temporary bound to a reference member in a constructor initializer list persists only until the constructor exits, not as long as the object exists.

This can be found in the draft C++ standard section 12.2 Temporary objects paragraph 5 which includes the following bullet

— A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.

Sign up to request clarification or add additional context in comments.

Comments

2

A temporary will be created and the reference is bound to that temporary (C++03 8.5.3.5). The temporary will be destroyed at the end of the constructor call, leaving a dangling reference. This is specified in C++03 12.2.5:

A temporary bound to a reference member in a constructor's ctor-initializer (12.6.2) persists until the constructor exits.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.