我有一个函数调用
class MyClass {
static std::string getName(void) {
return getMyName(void); // Returning by value as well
}
};
现在,如果我在一个类的构造函数中使用这个函数
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;
}
这是移动语义的正确用法吗?如何确保函数使用移动语义?
我正在努力学习通过移动语义来实现效率,所以如果这是一个愚蠢的问题,请道歉。
我查过了
http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html
Is this correct usage of C++ 'move' semantics?
这是一个很好的解释,但在确保函数是否使用移动语义方面需要澄清。
发布于 2013-07-22 09:20:47
这里不需要使用std::move
:
m_name(std::move(MyClass::getName())) {} // no need to use std::move
getName()
返回一个副本,它已经是一个右值。
只需像平常一样执行此操作:
m_name(MyClass::getName()) {}
如果需要,将自动使用move构造函数。(编译器可以完全省略副本,将MyClass::getName()
的返回值直接构造到m_name
中,这会更好)。
至于这一点:
const std::string& name() const { return m_name; }
这里也不需要做任何特殊的事情。你不想改变m_name
,所以你不应该使用std::move
,而应该使用常规的常量左值引用。
需要std::move
的最常见情况是在创建自己的移动构造函数时:
class AnotherClass {
public:
AnotherClass(AnotherClass &&that) :
m_name(std::move(that.m_name))
{
}
};
这是因为尽管that
被声明为右值引用,但在构造函数中,that
的行为类似于常规的左值引用。
https://stackoverflow.com/questions/17778636
复制相似问题