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

时光总嘲笑我的痴心妄想 提交于 2019-12-23 09:48:47

问题


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“.

Do I need to overload each function which normally would accept const lvalue reference to benefit from the rvalue references?

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.

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.)


回答1:


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.



来源:https://stackoverflow.com/questions/7587067/do-i-need-to-overload-methods-accepting-const-lvalue-reference-for-rvalue-refere

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!