xmllmx
xmllmx

Reputation: 42369

Does C++11 guarantee a dying object will be moved rather than copied as an argument?

#include <vector>

using namespace std;

void f(const vector<int>&) {}
void f(vector<int>&&) {}

int main()
{
    {
        vector<int> coll;

        //
        // coll is dying, so,
        // "f(coll)" will call "f(const vector<int>&)" or
        // "f(vector<int>&&)" as per C++11?
        //
        f(coll); 
    }
}

In the code above, coll is dying; so, f(coll) will call f(const vector<int>&) or f(vector<int>&&) as per C++11?

Upvotes: 3

Views: 140

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136355

If f(coll) called f(vector<int>&&) instead of f(const vector<int>&) that would be a violation of the standard, because it would pick the wrong function overload.

It would also be rather confusing if the resolution of the call was different depending on where the call is located and whether there are any subsequent statements after the call using coll.

The special treatment is given to return values only:

If expression is an lvalue expression and the conditions for copy elision are met, or would be met, except that expression names a function parameter, then overload resolution to select the constructor to use for initialization of the returned value is performed twice: first as if expression were an rvalue expression (thus it may select the move constructor or a copy constructor taking reference to const), and if no suitable conversion is available, overload resolution is performed the second time, with lvalue expression (so it may select the copy constructor taking a reference to non-const).

Upvotes: 5

Related Questions