其他分享
首页 > 其他分享> > 这个有效的C代码是否符合标准?

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

作者:互联网

我有这个示例代码:

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中是否仍然有效?

解决方法:

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

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

标签:c,scope,reference,const-reference
来源: https://codeday.me/bug/20190730/1580547.html