gpt4 book ai didi

c++11 move 不生效?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:14:43 25 4
gpt4 key购买 nike

我测试了c++11的 move 函数,但是没有生效。谁能告诉我为什么?谢谢。代码如下:

class Base {
public:
Base() { cout << "Base" << endl;}
~Base() { cout << "~Base" << endl;}

Base(const Base& base) { cout << "Copy" << endl; }
Base& operator=(const Base& base) {cout << "operator=" << endl;}

Base(Base&& base) { cout << "move" << endl;}
Base& operator=(Base&& base) { cout << "move=" << endl;}
};

Base b;

Base&& GetResult() {
return std::move(b);
}

int main() {
Base&& tmp = GetResult();

cout << &b << endl;
cout << &tmp << endl;

}

输出:

 Base
0x6013a0
0x6013a0
~Base

为什么 move copymove operator= 不被调用?为什么地址是一样的?

最佳答案

为了补充现有的优秀答案,我认为这里的主要混淆点是 std::move 的作用。

std::move 不 move 。

它的名字非常难

它只会给你一个 xvalue,指的是你给它的任何东西;此 xvalue 将绑定(bind)到右值引用,而左值则不会。这意味着 std::move 可以 的结果被提供给 move 构造函数或 move 赋值运算符。但是,它不会为您做这些,您也不会在这里做。


Given such strong criticism for the naming, surely you have an alternative suggestion
user2079303

这是一个老生常谈的话题,但是the creator of C++ suggests std::rval , 和 one of the architects of modern C++ suggests std::rvalue_cast (即使你实际上得到了一个 xvalue)。

就我个人而言,我认为 std::moveable 会是一个很好的中间立场。

关于c++11 move 不生效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43523753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com