我无法理解 c++11 中的 move 函数。
来自here ,我得到了以下内容:
Although note that -in the standard library- moving implies that the moved-from object is left in a valid but unspecified state. Which means that, after such an operation, the value of the moved-from object should only be destroyed or assigned a new value; accessing it otherwise yields an unspecified value.
在我看来,在 move() 之后,移出的对象已经“清晰”了。不过,我做了以下测试:
std::string str = "abcd";
std::move(str);
std::cout<<str;
我的屏幕上出现 abcd
。
那么str
已经被破坏了吗?如果是这样,我可以获得 abcd
因为我很幸运?或者我误解了函数move
?
此外,当我阅读C++ Primer时,我得到了这样的代码:
class Base{/* ... */};
class D: public Base{
public:
D(D&& d): Base(std::move(d)){/* use d to initialize the members of D */}
};
我现在很困惑。如果函数move
会清除对象,那么参数d
也会被清除,我们怎么能“用d来初始化D的成员”呢?
最佳答案
std::move
实际上并没有做任何事情。它大致类似于强制转换表达式,因为返回值是原始对象,但处理方式有所不同。
更准确地说,std::move
以某种形式返回对象,该形式适合其资源因某些其他目的而被“窃取”。原始对象或多或少仍然有效(您只应该对它做某些特殊的事情,尽管这主要是一个约定问题,不一定适用于非标准库对象),但被盗的资源不会不再属于它,并且一般不会再被它引用。
但是! std::move
本身并不进行窃取。它只是让偷窃变得被允许。由于您没有对结果做任何事情,更不用说做一些可以利用这个机会的事情,所以没有任何东西被窃取。
关于C++11:如何理解函数 move,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36002627/