C++11 STL 中最常使用移动语义的地方是什么?
What are the most common places that move semantics is used in C++11 STL?
我知道 std::vector<T>::push_back()
支持移动语义。因此,当我将命名的临时实例添加到向量时,我可以使用 std::move()
.
STL中还有哪些常见的地方我应该养成添加的习惯std::move()
I know that std::vector<T>::push_back()
has move semantics support.
push_back
的支持只是一个额外的重载,它采用 右值引用 ,因此向量中的新值 T
可以是通过调用 T(T&&)
而不是 T(const T&)
来构建。优点是前者可以更有效地实现,因为它假定传递的 右值引用 以后永远不会被使用。
大多数标准库容器都在其 push/enqueue/insert 成员函数中添加了类似的重载。此外,添加了 emplacement 的概念 (例如 std::vector<T>::emplace_back
),其中值按顺序在容器内的适当位置构造避免不必要的临时工。安置应优先于 insertion/pushing.
So, when I add a named temporary instance to a vector, I can use std::move()
.
"Named temporary" 真的没有多大意义。这个想法是你有一个你不再关心的 lvalue,你想通过使用 std::move
把它变成一个临时值。示例:
Foo foo;
some_vector.emplace_back(std::move(foo));
// I'm sure `foo` won't be used from now on
请记住 std::move
并不特殊:它的字面意思是 static_cast<T&&>
。
What are the other common places in the STL that I should grow the habit to add std::move
?
这是一个非常广泛的问题 - 您应该在任何有意义的地方添加 std::move
,而不仅仅是在标准库的上下文中。如果你有一个 lvalue 你知道你不会再在特定的代码路径中使用,并且你想将它传递 it/store 到某个地方,然后 std::move
它。
我知道 std::vector<T>::push_back()
支持移动语义。因此,当我将命名的临时实例添加到向量时,我可以使用 std::move()
.
STL中还有哪些常见的地方我应该养成添加的习惯std::move()
I know that
std::vector<T>::push_back()
has move semantics support.
push_back
的支持只是一个额外的重载,它采用 右值引用 ,因此向量中的新值 T
可以是通过调用 T(T&&)
而不是 T(const T&)
来构建。优点是前者可以更有效地实现,因为它假定传递的 右值引用 以后永远不会被使用。
大多数标准库容器都在其 push/enqueue/insert 成员函数中添加了类似的重载。此外,添加了 emplacement 的概念 (例如 std::vector<T>::emplace_back
),其中值按顺序在容器内的适当位置构造避免不必要的临时工。安置应优先于 insertion/pushing.
So, when I add a named temporary instance to a vector, I can use
std::move()
.
"Named temporary" 真的没有多大意义。这个想法是你有一个你不再关心的 lvalue,你想通过使用 std::move
把它变成一个临时值。示例:
Foo foo;
some_vector.emplace_back(std::move(foo));
// I'm sure `foo` won't be used from now on
请记住 std::move
并不特殊:它的字面意思是 static_cast<T&&>
。
What are the other common places in the STL that I should grow the habit to add
std::move
?
这是一个非常广泛的问题 - 您应该在任何有意义的地方添加 std::move
,而不仅仅是在标准库的上下文中。如果你有一个 lvalue 你知道你不会再在特定的代码路径中使用,并且你想将它传递 it/store 到某个地方,然后 std::move
它。