Home > Back-end >  What does explicit *this object parameter offer in C 23?
What does explicit *this object parameter offer in C 23?

Time:10-18

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?

CodePudding user response:

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;
}
  • Related