我可以用什么代替std :: move()?

Mik*_*eir 4 c++ std rvalue-reference move-semantics c++11

我正在使用具有C ++ 0x规范的C ++编译器,并希望使我的move构造器成为环绕std :: wstring的String类。

class String {
public:
    String(String&& str) : mData(std::move(str.mData)) {
    }

private:
    std::wstring mData;
};
Run Code Online (Sandbox Code Playgroud)

在Visual Studio中,这完美无缺。在Xcode std::move()中不可用。

Pra*_*ian 5

std::move只需将其参数转换为右值引用即可。您可以编写自己的版本:

template<class T>
typename std::remove_reference<T>::type&&
move( T&& arg ) noexcept
{
  return static_cast<typename std::remove_reference<T>::type&&>( arg );
}
Run Code Online (Sandbox Code Playgroud)

  • @ PhoenixX_2 std :: move和std :: remove_reference是标准库的一部分。由于编译器已经知道右值引用,因此您应该只使用C ++ 11标准库,而不要尝试实现自己的`move()`。我猜您正在使用libstdc ++,并且应该考虑切换到libc ++。 (4认同)
  • @Phoenix-问题是,如果您使用的标准库不知道`move`,我敢打赌`wstring`仍会复制该字符串。如果您没有移动库,尝试移动将无济于事。 (2认同)