Is this C ++ code standard?

I have this code example:

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();
}

Mostly, the constructor bothers me Test, where I save the reference to the constant in a temporary variable and use it in the method f. Will the temporary object reference remain valid inside f?

+3
source share
1 answer

It will not remain valid. The temporary object will be destroyed after initialization a. While you are invoking f, you are invoking undefined behavior by invoking test. Only the following is allowed:

// Valid - both temporary objects are alive until after the 
// full expression has been evaluated.
Test<>().f();
+7
source

Source: https://habr.com/ru/post/1779358/


All Articles