首先:
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
考虑到“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
这样做是正确的吗?有哪些需要注意的地方呢?
2) 我发现我的一个函数返回std::string
时,它自动调用了移动构造函数。在进入字符串的返回(感谢Aragorn),我注意到它调用了一个显式的移动构造函数。为什么string类有移动构造函数而vector没有呢?
我不需要对这个函数进行任何修改以利用移动语义:
// below, no need for std::string&& return value?
std::string AnyConverter::toString(const boost::any& _val) const
{
string ret;
// convert here
return(ret); // No need for static_cast<std::string&&> ?
}; // eo toString
3) 最后,我想进行一些性能测试,所以我得到的惊人快速的结果是因为std::move语义还是我的编译器(VS2010)也进行了一些优化呢?
(为简洁起见省略了_getMilliseconds()
的实现)
std::vector<int> v;
for(int a(0); a < 1000000; ++a)
v.push_back(a);
std::vector<int> x;
for(int a(0); a < 1000000; ++a)
x.push_back(a);
int s1 = _getMilliseconds();
std::vector<int> v2 = v;
int s2 = _getMilliseconds();
std::vector<int> v3 = std::move(x);
int s3 = _getMilliseconds();
int result1 = s2 - s1;
int result2 = s3 - s2;
结果显然很棒。result1是一个标准的赋值,用了630毫秒。第二个结果只用了0毫秒。这是这些东西的一个好性能测试吗?
我知道这对你们很多人来说很明显,但在我开始编写代码之前,我想确保我正确理解语义。
提前感谢!
static_cast<T&&>
而不是std::move
? - GManNickG