This question already has answers here:
What is move semantics?

(12 个回答)


4年前关闭。




我正在阅读 std 模板库书籍,但对 STL 容器章节中列出的以下详细信息感到困惑。
显然,它指定了 STD::VECTOR 操作和效果
Operation                     Effect

vector<Elem> c(c2)  | Copy constructor; creates a new vector as a copy of c2 (all elements are copied)
vector<Elem> c = c2 | Copy constructor; creates a new vector as a copy of c2 (all elements are copied)
vector<Elem> c(rv)  | Move constructor; creates a new vector, taking the contents of the rvalue rv (since C++11)
vector<Elem> c = rv | Move constructor; creates a new vector, taking the contents of the rvalue rv (since C++11)

显然,移动构造函数和复制构造函数的语法没有区别,它们究竟是什么时候被调用的?

最佳答案

假设您有一个按值返回 vector 的函数 f:

std::vector<int> f();

函数返回的值是一个右值。

然后假设您想调用此函数来初始化您的 vector :
std::vector<int> v = f();

现在编译器知道 f 返回的 vector 将不再使用,它​​是一个临时对象,因此复制这个临时对象没有意义,因为它无论如何都会被立即破坏。所以编译器决定调用移动构造函数。

关于c++ - C++ 编译器如何决定何时为 std::vector 或任何对象调用移动构造函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39347986/

10-11 22:23
查看更多