【发布时间】:2014-01-08 19:31:00
【问题描述】:
我想使用该类的构造函数将一个大型容器从返回值移动到另一个类。如何制定参数以确保它最终不会被复制?
/* for the sake of simplicity, imagine this typedef to be global */
typedef std::unordered_map<std::string, unsigned int> umap;
umap foo()
{
umap m; /* fill with lots of data */
return m;
}
class Bar
{
public:
Bar(umap m) : bm(m) { }
private:
umap bm;
};
Bar myBar(foo()); // run foo and pass return value directly to Bar constructor
上述公式会触发适当的行为,还是我需要将构造函数的参数指定为右值引用,就像容器为自己的移动语义所做的那样?
public:
Bar(umap&& m) : bm(m) { }
或
public:
Bar(umap&& m) : bm(std::move(m)) { }
...?
【问题讨论】:
-
我认为 Scott Meyer 在这里对此发表了评论:channel9.msdn.com/Events/GoingNative/2013/…!
标签: c++ c++11 parameters move-semantics