【发布时间】:2010-04-24 14:01:28
【问题描述】:
我正在尝试在我的容器库中实现以下优化:
- 插入左值引用元素时,将其复制到内部存储;
- 但在插入 rvalue-referenced 元素时,如果支持,移动它。
优化应该是有用的,例如如果包含的元素类型类似于std::vector,则在可能的情况下移动将大大加快速度。
但是,到目前为止,我无法为此设计任何工作方案。我的容器相当复杂,所以我不能多次重复insert() 代码:它很大。我想将所有“真实”代码保留在某个内部助手中,比如do_insert()(可能是模板化的),而各种类似insert() 的函数只会用不同的参数调用它。
我最好的代码(当然是原型,没有做任何实际的事情):
#include <iostream>
#include <utility>
struct element
{
element () { };
element (element&&) { std::cerr << "moving\n"; }
};
struct container
{
void insert (const element& value)
{ do_insert (value); }
void insert (element&& value)
{ do_insert (std::move (value)); }
private:
template <typename Arg>
void do_insert (Arg arg)
{ element x (arg); }
};
int
main ()
{
{
// Shouldn't move.
container c;
element x;
c.insert (x);
}
{
// Should move.
container c;
c.insert (element ());
}
}
但是,这至少不适用于 GCC 4.4 和 4.5:它永远不会在 stderr 上打印“移动”。或者是我想要的不可能实现,这就是为什么emplace()-like 函数首先存在?
【问题讨论】:
标签: c++ c++11 move-constructor