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

Des*_*old 6 c++ this c++23 explicit-object-parameter

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

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

但是我很困惑,如果这个参数在不使用模板的情况下创建“副本”,因为没有引用,或者显式this参数是否有自己的值类别规则?

自从:

struct hello {
  void func() {}
};
Run Code Online (Sandbox Code Playgroud)

可能相当于:

struct hello {
  void func(this hello) {}
};
Run Code Online (Sandbox Code Playgroud)

但它们的类型不同,因为对于&hello::func,第一个给出void(hello::*)(),而第二个给出void(*)(hello)

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

struct hello {
  int data;
  void func(this hello self) {
    self.data = 22;
  }
};
Run Code Online (Sandbox Code Playgroud)

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

Bri*_*ian 7

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

因此,在您的示例中,self参数被修改然后被销毁。调用者的hello对象永远不会被修改。如果要修改调用者的对象,则需要self通过引用获取:

void func(this hello& self) {
  self.data = 22;
}
Run Code Online (Sandbox Code Playgroud)