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

时间:2010-12-09 09:17:20

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

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

1 个答案:

答案 0 :(得分:7)

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

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