如何定义一个函数来处理移动语义和复制语义? [英] How to define a function to work with move semantics and copy semantics?

查看:53
本文介绍了如何定义一个函数来处理移动语义和复制语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在实现一个集合并且我想向其中添加一个元素,例如.

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 addthe 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆