今晚我一直在看一些我过去几天一直在研究的代码,并开始阅读移动语义,特别是std :: move.我有几个问题要求专业人士确保我走正确的道路而不做任何愚蠢的假设!
首先:
1)最初,我的代码有一个返回大向量的函数:
template<class T> class MyObject
{
public:
std::vector<T> doSomething() const;
{
std::vector<T> theVector;
// produce/work with a vector right here
return(theVector);
}; // eo doSomething
}; // eo class MyObject
Run Code Online (Sandbox Code Playgroud)
鉴于"theVector"在这个和"扔掉"中是暂时的,我将该函数修改为:
std::vector<T>&& doSomething() const;
{
std::vector<T> theVector;
// produce/work with a vector right here
return(static_cast<std::vector<T>&&>(theVector));
}; // eo doSomething
Run Code Online (Sandbox Code Playgroud)
它是否正确?这样做有什么陷阱吗?
2)我在一个函数中注意到它返回std::string它自动调用移动构造函数.调试返回字符串(thankyou,Aragorn),我注意到它称为显式移动构造函数.为什么有一个字符串类而不是矢量?
我没有必要对此函数进行任何修改以利用移动语义:
// below, no need for std::string&& return value?
std::string AnyConverter::toString(const boost::any& _val) const
{
string ret;
// convert here
return(ret); // No …Run Code Online (Sandbox Code Playgroud)