简体   繁体   English

我是否需要重载显式接受const左值引用作为右值引用的方法?

[英]Do I need to overload methods accepting const lvalue reference for rvalue references explicitly?

currently I'm playing around with rvalue reference (C++11, g++ with gnu++x0) and I want to implement move semantics in my classes, because it just feels „right“. 目前,我正在使用右值引用(C ++ 11,带有gnu ++ x0的g ++),并且我想在我的类中实现移动语义,因为它感觉“不错”。

Do I need to overload each function which normally would accept const lvalue reference to benefit from the rvalue references? 我是否需要重载通常会接受const lvalue引用的每个函数以从rvalue引用中受益?

Let's say this is my example class: 假设这是我的示例类:

class Person {
public:
    Person() = default;
    Person(std::string &name);
    Person(const Person &rhs);
    Person(Person &&rhs);

    Person& operator=(const Person &rhs);
    Person& operator=(Person &&rhs);

    std::string& get_name() const;
    void set_name(const std::string &name);
private:
    std::string name_;
}

/* snip */

void Person::set_name(const std::string &name)
{
    this->name_ = name;
}

I now want to use the setter with rvalue references and eliminate unnecessary copies. 我现在想将setter与rvalue引用一起使用,并消除不必要的副本。

Person test("Jon Doe");
test.set_name("Jon Doe2");

Do I really need to overload every method this way? 我真的需要这样重载每种方法吗?

void Person::set_name(std::string &&name)
{
    this->name_ = std::move(name);
}

This seems very redundant to me. 这对我来说似乎很多余。 Is there any way to implement this easier? 有什么办法可以更轻松地实现这一目标?

Thanks! 谢谢!

(I read stackoverflow often, but this is my first question. So please give me hint if I'm doing something wrong.) (我经常阅读stackoverflow,但这是我的第一个问题。因此,如果我做错了事,请给我提示。)

Write one function. 编写一个函数。 Take it in by value, then move it. 按价值计入,然后移动。

void Person::set_name(std::string name)
{
    this->name_ = std::move(name);
}

Let the std::string decide how to copy itself. 让std :: string决定如何复制自身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM