4 ms·
C++ does not currently have such methods- all `this` parameters are always by (some kind of) reference. (This doesn't stop you from moving out of `*this`, but C
by Rusky 5y ago
C++ does not currently have such methods- all `this` parameters are always by (some kind of) reference. (This doesn't stop you from moving out of `*this`, but C++ moves require the source object to remain valid, and I'm not sure I've ever seen that in the wild anyway!)
This will change in C++23 with "explicit this", but then the `this` parameter will no longer be implicit and that translated elision rule will no longer apply either.
So in today's C++ your example might look something like this:
struct God {
Mortal transform() && { // Take an rvalue reference for `*this`, I guess?
return Mortal{ /* Move some fields out of `*this` probably? */ };
}
};
The elision rule does apply here even though we're moving out of `*this`, but again we are still taking a reference and the God object remains valid afterward anyway.
With "explicit this" you could instead write something like this:
struct God {
Mortal transform(this God self) { ... }
};
Now there's no reference and the rule ceases to apply. (Though in most cases you are still going to be leaving a valid, but now at least unrelated, God object behind- the only way to avoid that is to construct it directly in argument position so it stays a prvalue.)
- enedil 5y agoIn our codebase though we have some places where we do `delete this;` and later use placement new, to restore `this` to some valid state.
- Rusky 5y agoThat only seems tangentially related to me, but it is interesting, haha. Specifically that sounds like it would cause use-after-frees- if you actually `delete this` and then `new (this) Bla`, you're writing to memory that's already been returned to the allocator. Maybe you meant `this->~Bla()` rather than `delete this`? Or a custom `operator delete`?