13

I know that the type of this is a prvalue ("pure" rvalue) pointer, and that it may be made a pointer-to-const and/or pointer-to-volatile (affecting accesses to its instance variables), by appending the keywords const or volatile to the end of the function definition to which it belongs.

I also know that this is sometimes (incorrectly) described as being a const pointer, perhaps as a way of saying "you can't make an assignment to this". As an rvalue, it is inherently unassignable, and so there is no need for the concept of a const rvalue.

I also know that in C++11, there are cases where being an rvalue or an lvalue can affect call resolution, but I've tried to work through the possibilities, and I'm not sure whether there's a case where it would actually matter to call resolution that this is an rvalue pointer rather than a const lvalue pointer.

Is there a case where this distinction makes a real difference, from a programmer's perspective, such as a context where an rvalue pointer can be used that a const lvalue pointer cannot be used, where a const lvalue pointer can be used that an rvalue pointer cannot, or where the difference affects call resolution?

Community
  • 1
  • 1
Theodore Murdock
  • 1,538
  • 1
  • 13
  • 28

1 Answers1

6

An obvious consequence of this being an prvalue is that &this is illegal. So, built-in unary operator & makes an example of "where a const lvalue pointer can be used that an rvalue pointer cannot". For the very same fundamental reason direct binding of references to this is not possible.

Also, prvalue-ness of this means that this itself cannot be const or volatile, since scalar rvalues cannot have cv-qualified types.

It is probably hard to build non-esoteric real-life code examples based on these distinctions.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • 1
    Another consequence is that capturing `this` in lambda is a special language case (as you can only capture lvalues usually) – Revolver_Ocelot Feb 09 '16 at 22:57
  • Am I right in saying that, because `&this` is illegal, we also can't pass `this` to a function that takes an rvalue reference? Would that be sufficient to prove that call resolution of a call that passes `this` cannot be affected by its rvalue status? Or might something like [blocking the passing of rvalues as arguments](http://stackoverflow.com/questions/6307526/c0x-const-rvalue-reference-as-function-parameter) still apply to `this`? – Theodore Murdock Feb 10 '16 at 00:48
  • a real-world legitimate (?) use case of taking the address of `this`: I want to use memcpy() to copy the pointer of the current object to a buffer in order to use it as a unique identifier for logging purposes. E.g.: `std::vector log(128); memcpy(log.data(), &this, sizeof(this)); // log relevant data ...` But that's not allowed, so I have to recur to using a temporary intermediate value instead. – oromoiluig Jul 18 '23 at 19:47