这个有效的C++代码是否符合标准?

Nav*_*een 3 c++ scope reference const-reference

我有这个示例代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

基本上我担心Test我将const引用存储到临时变量并在methof中使用它的构造函数f.临时对象引用在内部f是否仍然有效?

Joh*_*itb 7

它不会保持有效.初始化后,临时对象将被销毁a.在f您调用时,通过调用调用未定义的行为test.只有以下内容有效:

// Valid - both temporary objects are alive until after the 
// full expression has been evaluated.
Test<>().f();
Run Code Online (Sandbox Code Playgroud)