C++11 是否保证一个垂死的对象将被移动而不是作为参数复制?
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);
}
}
在上面的代码中,coll
即将死去;所以,f(coll)
将根据 C++11 调用 f(const vector<int>&)
或 f(vector<int>&&)
?
如果 f(coll)
调用了 f(vector<int>&&)
而不是 f(const vector<int>&)
这将违反标准,因为它会选择错误的函数重载。
如果根据调用的位置和调用后是否有任何后续语句使用coll
调用的分辨率不同,也会很混乱。
特殊待遇仅给予return values:
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).
#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);
}
}
在上面的代码中,coll
即将死去;所以,f(coll)
将根据 C++11 调用 f(const vector<int>&)
或 f(vector<int>&&)
?
如果 f(coll)
调用了 f(vector<int>&&)
而不是 f(const vector<int>&)
这将违反标准,因为它会选择错误的函数重载。
如果根据调用的位置和调用后是否有任何后续语句使用coll
调用的分辨率不同,也会很混乱。
特殊待遇仅给予return values:
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).