gpt4 book ai didi

c++ - C++11 是否保证一个垂死的对象将被 move 而不是作为参数复制?

转载 作者:太空狗 更新时间:2023-10-29 20:35:30 26 4
gpt4 key购买 nike

#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)会调用f(const vector<int>&)f(vector<int>&&)根据 C++11?

最佳答案

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

关于c++ - C++11 是否保证一个垂死的对象将被 move 而不是作为参数复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42509788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com