xmllmx xmllmx -4 years ago 88
C++ Question

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()
while (true)
vector<int> coll;

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

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

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download