如何定义一个函数来处理移动语义和复制语义? [英] How to define a function to work with move semantics and copy semantics?
问题描述
假设我正在实现一个集合并且我想向其中添加一个元素,例如.
Suppose that I am implementing a collection and I want to add an element to it, something like.
template <typename T>
class MyCollection
{
void add(const T& element);
};
现在,由于添加元素通常意味着复制它,因此出于效率原因,使用以下版本的 add 以及 void add(T&& element)
.现在的问题是,显然这两个函数的代码是完全一样的,只是参数类型不同.目前我对C++的掌握是有限的,但我想知道是否有一种简单而惯用的方法来编写add
函数一次而无需重写两次?
Now, since adding element usually means copying it, for efficiency reason it makes sense to have the
following version of add as well void add(T&& element)
. Now the problem is that, obviously the code for both functions is exactly the same, with only difference being the argument type. My command of C++ is limited at the moment, but I would like to know whether there is a simple and idiomatic way to write the add
the function once without rewriting it twice?
推荐答案
实际上这是通过定义一个重载来解决的:
In fact this is solved by defining a single overload:
void add(T element) {
where_it_is_actually_stored.insert(std::move(element));
}
接下来,根据您是添加左值、由移动的左值生成的右值还是临时对象,编译器将解析适当的构造函数,以便复制或移动您的值参数.
Next, depending on whether you're adding a lvalue, a rvalue made from a moved lvalue, or a temporary object, the compiler will resolve an appropriate constructor so your value argument would be either copied or moved.
这篇关于如何定义一个函数来处理移动语义和复制语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!