Binding temporary to const reference in c'tor initializer list
Asked Answered
H

1

12

Section 12.2.5 in C++03 says "A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits"
So I tried following program

#include<iostream>
using namespace std;

struct foo
{
  foo()
  {
    cout<<"foo c'tor"<<endl;
  }
  ~foo()
  {
    cout<<"foo d'tor"<<endl;
  }
};

struct bar
{
  const foo &ref;
  bar():ref(foo()) 
  {
    cout<<"bar c'tor"<<endl;
  }

};

int main()
{
  bar obj;
}    

The output I get is :

foo c'tor
foo d'tor
bar c'tor

Now according to standard, temporary generated by foo() in c'tor init-list of bar's c'tor will be destroyed after bar's c'tor so foo d'tor should be printed after bar c'tor
but it's other way around.
Please explain the reason.

Hydra answered 18/1, 2011 at 6:31 Comment(6)
What happens if you reference 'ref' inside the constructor? Maybe the compiler decides that since it isn't actually used it can destroy it earlier.Balkan
VS2008 produces foo,bar,foo output where as gcc 4.3.4 produces foo,foo,bar output. Interesting...Symmetry
g++ bug, report.Fascinating
@Tal Pressman : Yes I tried that too : ideone.com/nm9NAHydra
just for info: in MS VS warning C4413: 'bar::ref' : reference member is initialized to a temporary that doesn't persist after the constructor exitsPelargonium
Re-running @HappyMittal's code, it looks like this is now fixed: ideone.com/zJwC3ZUptown
P
3

I have tried this with MS VS 2010, and it gives me the output also gives warning during compile:

warning C4413: 'bar::ref' : reference member is initialized to a temporary that doesn't persist after the constructor exits

foo c'tor
bar c'tor
foo d'tor
Press any key to continue . . .

It seems that MS VS 2010 implements specification correctly. I agree that it is a bug for g++.

EDIT: ref should be initialized in constructor`s initialize list.

Pelargonium answered 18/1, 2011 at 9:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.