显式 *this 对象参数在 C++23 中提供什么?

问题描述 投票:0回答:1

在 C++23 中,推导这个最终被添加到标准中。

根据我从提案中读到的内容,它开辟了一种创建 mixin 的新方法,并且可以创建递归 lambda。

但是我很困惑,如果这个参数在不使用模板的情况下创建“副本”,因为没有引用,或者显式

this
参数是否有自己的值类别规则?

自:

struct hello {
  void func() {}
};

可能相当于:

struct hello {
  void func(this hello) {}
};

但它们的类型不同,因为对于

&hello::func
,第一个给出
void(hello::*)()
,而第二个给出
void(*)(hello)

例如,我有这个简单的功能:

struct hello {
  int data;
  void func(this hello self) {
    self.data = 22;
  }
};

this
参数不需要作为引用来改变
hello
类型的值吗?或者它基本上和以前一样遵循成员函数的 cv-ref 限定符规则?

c++ this c++23 explicit-object-parameter
1个回答
6
投票

论文第 4.2.3 节提到“按值

this
”是明确允许的,并且可以实现您所期望的功能。第 5.4 节给出了一些您何时需要这样做的示例。

因此在您的示例中,

self
参数被修改然后被销毁。调用者的
hello
对象永远不会被修改。如果要修改调用者的对象,需要通过引用来获取
self

void func(this hello& self) {
  self.data = 22;
}
© www.soinside.com 2019 - 2024. All rights reserved.