#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
}

As I have been knowing, non-const referencing to a temporary object is ill-formed. However, the code above shows it seems legal in C++. Why?

My compiler is VC++ 2013.

有帮助吗?

解决方案

The code does not really show that it is legal in C++. It simply shows that your compiler supports a non-standard compiler extension. You have to consult your compiler docs to find out whether the lifetime of the temporary is extended. Your experiment appears to show that it is extended.

Nevertheless, your code is ill-formed in standard C++. If you disable compiler extensions in that compiler by using /Za option, it will also refuse to accept your code:

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

Alternatively, to avoid using /Za (which is apparently broken) you can do

#pragma warning(error : 4239)

or change the corresponding project setting under C/C++ -> Advanced -> Treat Specific Warnings As Errors to prohibit this specific functionality in a more targeted manner.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top