mardi 10 octobre 2017

Taking address of an rvalue allowed?

I am practicing things described Here to learn the concept of lvalue and rvalue.

However, when I contrive my own example as follows, I find it compiles and runs without any error (using VS2017). I have learnt that in case 1, it is the same as calling

produceA(10).operator=(A()) 

and thus is legal. But, I still don't understand why case 2 and 3 are allowed. In fact, case 2 even contradicts the example given in the article. Am I actually getting the addresses of rvalues in these 2 cases? Do they lead to undefined behavior?

#include <string>

class A
{
    int data = 1;
public:
    A() = default;

    A(int in)
    : data(in)
    {}

    A& operator=(const A& rhs)
    {
        data = rhs.data;
        return *this;
    }
};

A produceA(int i)
{
    A a(i);
    return a;
}


int main()
{
    // case 1
    produceA(10) = A();

    // case 2
    A* pa = &produceA(10);    // rvalue?

    // case 3
    std::string* pstr = &std::string("Temp");    // rvalue?

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire