c++11 - Is this correct usage of move semantics -
i have function call
class myclass { static std::string getname(void) { return getmyname(void); // returning value } };
now if use function in constructor of class
class anotherclass { public: anotherclass(void) : m_name(std::move(myclass::getname())) {} // 1. std::move used const std::string& name(void) const { // 2. should use std::string&& (without consts) // .... need make sure value cannot changed (e.g, name() = "blah";) // if std::string&& used should use calling name() call function using move or should leave is? return m_name; } private: std::string m_name; }
is correct usage of move semantics? how can ensure function using move semantics?
i trying learn implement efficiency move semantics apology if dumb question.
i have checked
http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html
is correct usage of c++ 'move' semantics?
a great explanation need clarafication on ensuring if function using move semantics.
there no need use std::move
here:
m_name(std::move(myclass::getname())) {} // no need use std::move
getname()
returns copy, rvalue.
just would:
m_name(myclass::getname()) {}
the move constructor used automatically, if needed @ all. (the compiler may omit copy altogether , construct return value of myclass::getname()
directly m_name
, better).
as this:
const std::string& name() const { return m_name; }
there no need special here either. don't want m_name
changed, shouldn't use std::move
, , should using regular const lvalue reference.
the common situation need std::move
when creating own move constructor:
class anotherclass { public: anotherclass(anotherclass &&that) : m_name(std::move(that.m_name)) { } };
this because though that
declared rvalue reference, inside constructor, that
behaves regular lvalue reference.
Comments
Post a Comment