假设我有一些通用 T 对象的向量:
std::vector<T> vector_of_ts = {...};
该向量本质上是一个堆分配的 T 对象数组,在底层。现在,假设我有以下内容:
std::unique_ptr<T> t = std::make_unique<T>(...);
这又是一个底层的堆分配的 T 对象。是否可以通过移动该对象将其推回向量,而不需要制作临时/额外的副本?比如:
vector_of_ts.move(*t)
vector_of_ts.emplace_back(std::move(*t))
可以让你将 T 从 unique_ptr 移动到向量中:example
#include <memory>
#include <vector>
struct T
{
// Can't be copied
T() = default;
T(const T&) = delete;
T(T&&) = default;
T &operator=(const T&) = delete;
T &operator=(T&&) = default;
};
int main()
{
std::vector<T> vector_of_ts;
std::unique_ptr<T> t = std::make_unique<T>();
// error: use of deleted function T::T(const T&)
vector_of_ts.emplace_back(*t);
// Success
vector_of_ts.emplace_back(std::move(*t));
}
请注意,移动后,t
指向移出的
T
对象。该对象的状态取决于移动构造函数的作用(例如,对于
std::string
,移出的对象将为空)。