Majid Q.
Majid Q.

Reputation: 798

Is this correct usage of move semantics

I have a function call

class MyClass {
    static std::string getName(void) {
        return getMyName(void); // Returning by value as well
    }
};

Now if I use this function in constructor of a class

class AnotherClass {
public:
    AnotherClass(void) :
        m_name(std::move(MyClass::getName())) {} // 1. std::move used

    const std::string& name(void) const {   // 2. Should I use std::string&& (without consts)
                                            //    .... but I also need to make sure value cannot be changed (e.g, name() = "blah";)
                                            //    if std::string&& will be used should I use it simply by calling name() to call function using move or should I leave it as is?
        return m_name;
    }
private:
    std::string m_name;
}

Is this correct usage of move semantics? How can I ensure a function is using move semantics?

I am trying to learn to implement efficiency by move semantics so apology if its dumb question.

I have checked

What are move semantics?

http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html

Is this correct usage of C++ 'move' semantics?

a great explanation but need clarafication on ensuring if function is using move semantics.

Upvotes: 1

Views: 97

Answers (1)

Vaughn Cato
Vaughn Cato

Reputation: 64308

There is no need to use std::move here:

   m_name(std::move(MyClass::getName())) {} // no need to use std::move

getName() returns a copy, which is already an rvalue.

Just do this like you normally would:

   m_name(MyClass::getName()) {}

The move constructor will be used automatically, if it is needed at all. (The compiler may very well omit the copy altogether and construct the return value of MyClass::getName() directly into m_name, which is even better).

As for this:

const std::string& name() const { return m_name; }

there is no need to do anything special here either. You don't want m_name to be changed, so you shouldn't use std::move, and you should be using a regular const lvalue reference.

The most common situation where you need std::move is when you are creating your own move constructor:

class AnotherClass {
public:
    AnotherClass(AnotherClass &&that) :
        m_name(std::move(that.m_name))
    {
    }
};

This is because even though that is declared as an rvalue reference, inside the constructor, that behaves like a regular lvalue reference.

Upvotes: 2

Related Questions