سؤال

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 ?

هل كانت مفيدة؟

المحلول

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();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top