3

I have this sample code:

struct A
{
    bool test() const
    {
        return false;
    }
};


template <typename T = A>
class Test
{
public:
    Test(const T& t = T()) : t_(t){}

    void f()
    {
        if(t_.test())
        {
            //Do something
        }
    }
private:
    const T& t_;
};

int main()
{
    Test<> a;
    a.f();
}

Basically I am worried about the constructor of Test where I am storing a const reference to a temporary variable and using it in methof f. Will the temporary object reference remains valid inside f ?

Naveen
  • 74,600
  • 47
  • 176
  • 233
  • 1
    I think - NO. The compiler can't track (in general case) where the reference is going and if it's stored persistently. But the simplest is to write a sample app and see what happens. – valdo Dec 09 '10 at 09:21
  • It works on VS2008, but I am not too convinced its right though. – Naveen Dec 09 '10 at 09:22

1 Answers1

7

It won't remain valid. The temporary object will be destroyed after initializing a. At the time you call f you invoke undefined behavior by calling test. Only the following is valid:

// Valid - both temporary objects are alive until after the 
// full expression has been evaluated.
Test<>().f();
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • Are you sure? `A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits. A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call.` - this being the first case, i don't know if it is valid ... – etarion Dec 09 '10 at 09:30
  • @etarion, 12.6.2 talks about temporary expressions. I.e expressions that refer directly to a temporary object. In this case, we initialize a reference member by an expression that does not refer directly to a temporary object, but rather through a reference binding in between. This is not said explicitly in there, but it is what is meant. So, you have to apply the second case. – Johannes Schaub - litb Dec 09 '10 at 09:34
  • @etarion for making this clearer. Consider a few examples: `struct A { A& f() { return *this; } };`. The intention is that `A().f().f()` is valid, even though the text says "A temporary bound to the returned value in a function return statement (6.6.3) persists until the function exits." – Johannes Schaub - litb Dec 09 '10 at 09:41
  • It may be unclear at first, but considering that if `Test<>().f();` should be an exact equivalent of `Test<>(A()).f();` it should become apparent how the second case applies? – visitor Dec 09 '10 at 10:07