Question

#include<iostream>
#include<vector>

struct Foo
{
    int *nb;

    Foo() :nb(new int(5)){}

    ~Foo(){ delete nb; }

    Foo(Foo&& f)
    {
            std::cout << "Move\n";
        nb = f.nb;
        f.nb = 0;
    }

}; 

std::vector<Foo> vec;

void func()
{ 
    vec.push_back(Foo()); 
}

int main()
{    
    func();
    std::cout << *(vec[0]).nb << "\n";
    std::cin.ignore();
}

Running:

> ./a.out
Move
5

Is it normal that under VS2013 vec.push_back(Foo()); call Foo(Foo&& f) ? I believed that Foo() was a lvalue.

Was it helpful?

Solution

This is normal. Since the instance that you create by calling Foo() is never assigned to a variable, the compiler will treat it as an r-value.

A short rule of thumb is that any object you create that is not given a name (ie no declaration) will be an r-value.

For a nice explanation of the details I recommend section 6.4.1 in The C++ Programming Language (4th Edition).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top