What does explicit *this object parameter offer in C++23?
Asked Answered
L

1

8

In C++23, deducing this is finally added to the standard.

Based on what I've read from the proposal, it opens up a new way of creating mixins, and possible to create recursive lambdas.

But I'm confused if this parameter creates a "copy" without using templates since there is no reference or does the explicit this parameter have its own rules of value category?

Since:

struct hello {
  void func() {}
};

may be the equivalent of:

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

But their type is different because for &hello::func, the first one gives void(hello::*)(), while the second one gives void(*)(hello)

For instance, I have this simple function:

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

Doesn't this parameter need to be a reference to change the value of hello type? Or it basically follows the cv-ref qualifier rules of member function as same as before?

Limber answered 18/10, 2021 at 0:46 Comment(1)
There's a "motivation" section in the proposal.Eudemonia
R
7

Section 4.2.3 of the paper mentions that "by-value this" is explicitly allowed and does what you expect. Section 5.4 gives some examples of when you would want to do this.

So in your example, the self parameter is modified and then destroyed. The caller's hello object is never modified. If you want to modify the caller's object, you need to take self by reference:

void func(this hello& self) {
  self.data = 22;
}
Rutharuthann answered 18/10, 2021 at 0:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.