c++ - 为什么我们可以非常量引用一个临时对象并延长它的生命周期?

标签 c++ c++11 reference object-lifetime temporary-objects

#include <iostream>

using namespace std;

struct A
{
    A()
        : _p(new int(1))
    {}

    ~A()
    {
        *_p = 0;

        delete _p;
        _p = nullptr;
    }

    int* _p;
};

int main()
{
    //
    // Let r_to_a reference to a temporary object
    //
    A& r_to_a = A();

    //
    // Is r_to_a still valid now?
    //
    cout << *r_to_a._p << endl; // Output : 1 instead of a run-time error
}

据我所知,对临时对象的非常量引用是不正确的。但是,上面的代码表明它在 C++ 中似乎是合法的。为什么?

我的编译器是 VC++ 2013。

最佳答案

代码并没有真正表明它在C++中是合法的。它只是表明您的编译器支持非标准编译器扩展。您必须查阅编译器文档以了解是否延长了临时文件的生命周期。您的实验似乎表明它已扩展。

但是,您的代码在标准 C++ 中的格式不正确。如果您使用 /Za 选项禁用该编译器中的编译器扩展,它也将拒绝接受您的代码:

error C2440: 'initializing' : cannot convert from 'A' to 'A &'

或者,为了避免使用 /Za(显然已损坏),您可以这样做

#pragma warning(error : 4239)

或者在C/C++ -> Advanced -> Treat Specific Warnings As Errors下更改相应的项目设置,更有针对性地禁止该特定功能。

关于c++ - 为什么我们可以非常量引用一个临时对象并延长它的生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19739991/

相关文章:

c++ - 如何将函数参数标记为输出

c++ - 为什么 std::lock_guard 不可移动?

c++ - boost::transform_iterator 不适用于 std::bind( &Pair::first, _1 )?

java - 两个 arrayList 对相同对象的引用

C++ 重写语法

c++ - 如何在 C++ 中编写可维护、快速、编译时的位掩码?

c++ - 错误 C2440 : 'initializing' : cannot convert from 'const temp1' to 'temp2'

c++ - 随机文件写入

c++ - 引用、逻辑运算符和循环条件

c++ - 为什么 const char* const & = "hello"可以编译?