我是一个move
语义初学者。这是代码吗:
template <typename... Args>
void foo(const Args & ... args){
map<tuple<Args...>, int> cache;
auto result = cache.emplace(move(make_tuple(args ...)),1);
//...
}
比以下方法更高效:
template <typename... Args>
void foo(const Args & ... args){
map<tuple<Args...>, int> cache;
tuple<Args...> t(args...);
auto result = cache.insert(make_pair(t,1));
//...
}
特别是如果args
包含一些大物体?
同样的问题,但有std::vector
(所以不需要make_pair
或make_tuple
)
由于这是为了记忆,因此这两种选择都不是一个好主意。
对于唯一键容器,emplace
和 insert
(除非insert
传递了value_type
- 即 pair<const Key, Value>
)可以无条件地分配内存并首先构造键值对,如果键已经存在,则销毁该对并释放内存;如果您的密钥已经存在,这显然是昂贵的。(他们需要这样做,因为在一般情况下,您必须先构造密钥,然后才能检查它是否存在,并且密钥必须直接在其最终位置构造。
但是,您还希望避免不必要地复制密钥,因此插入value_type
是不好的 - 其中的Key
是常量限定的,因此无法移动。
最后,您还需要避免额外的查找。不像内存分配那样昂贵,但保存它仍然很好。
因此,我们需要先查找密钥,并且仅在密钥不在映射中时才调用emplace
。在 C++11 中,只允许同构查找,因此您必须制作一个 args...
副本。
map<tuple<Args...>, int> cache;
auto key = std::make_tuple(args...);
auto it = cache.lower_bound(key); // *it is the first element whose key is
// not less than 'key'
if(it != cache.end() && it->first == key) {
// key already in the map, do what you have to do
}
else {
// add new entry, using 'it' as hint and moving 'key' into container.
cache.emplace_hint(it, std::move(key), /* value */);
}
在 C++14 中,您可以执行异构查找,这意味着您可以在实际需要时保存副本:
map<tuple<Args...>, int, less<>> cache; // "diamond functor" enables hetergeneous lookup
auto key = std::tie(args...); // this is a tuple<const Args&...> - a tuple of references!
auto it = cache.lower_bound(key); // *it is the first element whose key is
// not less than 'key'
if(it != cache.end() && it->first == key) {
// key already in the map, do what you have to do
}
else {
// add new entry, copying args...
cache.emplace_hint(it, key, /* value */);
}
template <typename... Args>
void foo(const Args & ... args){
map<tuple<Args...>, int> cache;
auto result = cache.emplace(move(make_tuple(args ...)),1);
//...
}
此代码应该更快。 emplace
执行就地构造(完美转发)。这应保证最小数量的构造和副本。但是,如果您对它们进行基准测试,这不会有什么坏处。
一般来说,尽可能使用"置地"。它应该始终是一个更好的选择。
首先:
auto result = cache.emplace(move(make_tuple(args ...)),1);
与
auto result = cache.emplace(make_tuple(args ...),1);
没有区别。 make_tuple(args...)
是暂时的,因此作为右值引用传递。此举不会增加任何东西。
不同的东西将是
tuple<Args...> t(args...);
auto result = cache.emplace(t, 1);
现在emplace()
接收一个左值引用,因此使用 std::p air 的复制构造函数而不是移动构造函数。
无论如何,如果大数据存在于任何args...
那么您的问题无论如何都出在其他地方。所有args
当前都作为左值引用传递。
您要做的是:
template <typename... Args>
void foo(Args && ... args){
map<tuple<Args...>, int> cache;
auto result = cache.emplace(make_tuple(forward<Args>(args)...)),1);
//...
}
如果将右值引用传递给foo()
,则forward<Args>(args)...
将其作为右值引用转发,从而导致移动而不是副本。如果使用左值引用调用foo()
,它将作为左值转发。