【发布时间】:2016-06-01 08:38:11
【问题描述】:
我有以下代码 (http://coliru.stacked-crooked.com/a/a0e5ff6ee73634ee):
#include <iostream
class A {
public:
explicit A(int a) {std::cout << "Main constructor" << std::endl;}
A(const A& a) {std::cout << "Copy constructor" << std::endl;}
A& operator =(const A& a) {std::cout << "Copy assignment" << std::endl; return *this;}
A(A&& a) {std::cout << "Move constructor" << std::endl;}
A& operator =(A&& a) {std::cout << "Move assignemnt" << std::endl; return *this;}
};
int main(void) {
std::cout << "\nA a3(A(0))" << std::endl;
A a3(A(0));
std::cout << "\nA a31(std::move(A(0)))" << std::endl;
A a31(std::move(A(0)));
std::cout << "\nA a4(*(new A(0)))" << std::endl;
A a4(*(new A(0)));
std::cout << "\nA a41(std::move(*(new A(0))))" << std::endl;
A a41(std::move(*(new A(0))));
}
这段代码写了以下内容:
A a3(A(0))
Main constructor
-> 在阅读了Move semantics and copy constructor 之后,我假设 RVO 发生了,a3 接管了 A(0) 的构造内容。
A a31(std::move(A(0)))
Main constructor
Move constructor
-> 好的
A a4(*(new A(0)))
Main constructor
Copy constructor
-> 为什么这不是移动构造函数而不是复制构造函数?
A a41(std::move(*(new A(0))))
Main constructor
Move constructor
-> 好的
编辑:
在更深入地分析问题后,我意识到@sameerkn 实际上是正确的。然而,正如@Angew 建议的那样,我试图分析静态变量发生了什么:这些变量没有像预期的那样移动(它们似乎被视为 const 变量)。
请参阅此处的完整代码:
http://melpon.org/wandbox/permlink/RCntHB9dcefv93ID
以下代码:
A a1(testStatic(1));
A a2(std::move(*(a1.getPointer()))); <-- Moving a dereference
std::cout << "\na1.mValue = " << a1.mValue << std::endl;
std::cout << "a2.mValue = " << a2.mValue << std::endl;
将返回:
Main constructor: This is my long String that should not be SSOed [STATIC]
Copy constructor: This is my long String that should not be SSOed [STATIC]
return aLocal
Move constructor <-- The dereferenced pointer is moved as expected
Destructor: [mValue moved away] <-- See here that the string was moved away
Move constructor <-- Moved again because of std::move
【问题讨论】:
标签: c++11 move-semantics