gpt4 book ai didi

c++ - 为什么左值不能改变自己。左值用户的意思是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:37:48 25 4
gpt4 key购买 nike

我在一篇原创文章中看到了这句话:

When we run sorted on an rvalue, it is safe to sort the data member directly. The object is an rvalue, which means it has no other users, so we can change the object itself. When we run sorted on a const rvalue or on an lvalue, we can’t change this object, so we copy data before sorting it

它说一个右值(临时)可以自行排序,因为它没有用户。左值无法对自身进行排序(对它的拷贝进行排序),因为它可能有用户。

什么是左值的使用者?背景是什么?

下面是一些示例代码。

#include <vector>
#include <algorithm>

using namespace std;

class Foo {
public:
Foo() { std::cout << "default construct" << std::endl;}
Foo(const Foo &f) : data(f.data) {std::cout << "copy construct" << std::endl;}
Foo sort() &&;
Foo sort() const &;
private:
vector<int> data;
};

Foo Foo::sort() && {
std::cout << "rvalue sort" << std::endl;
std::sort(data.begin(), data.end());
return *this;
}

Foo Foo::sort() const & {
std::cout << "lvalue sort" << std::endl;
return Foo(*this).sort();
}

最佳答案

rvalue 引用是一个不再被引用的对象。由于该对象不再被引用,该对象持有的任何内容都可以改变或移动到另一个对象,而不会影响对该对象的任何现有引用(它不再被引用)。这允许移动语义,这意味着可以移动通常必须复制到另一个对象的数据。

因此,使用您提供的示例代码...

int main(int argc, char *argv[]) {  

Foo x, y, z;

std::cout << "lvalue" << std::endl;

y = x.sort();

std::cout << "rvalue reference" << std::endl;

z = Foo().sort();

return 0;
}

我们有

default construct
default construct
default construct
lvalue
lvalue sort
copy construct
rvalue sort
copy construct
rvalue reference
default construct
rvalue sort
copy construct

首先发生的是 lvalue,它的 sort 方法被调用,它被复制并成为 rvalue 引用,然后被排序。

第二个是默认构造的对象没有名称,因此可以将其视为rvalue 引用。所以,rvalue引用sort方法被直接调用。

关于c++ - 为什么左值不能改变自己。左值用户的意思是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58423621/

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