Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning const 'this' pointer

Tags:

c++

if this is a const pointer to class's object how can you return a const pointer from non-const return type?

Class T
{
 public:
   T* func(){return this;}
};
like image 806
user963241 Avatar asked Dec 26 '10 05:12

user963241


3 Answers

Firstly, this is not a "const pointer". Where did you get that strange idea? Pointer this has scalar type and is not an lvalue, meaning that it can't possibly be "const" or "non-const". Pointer this is an rvalue and it is non-modifiable.

Secondly, the code in your question is valid regardless of whether the pointer involved is const or not. For example, the following code is valid for exactly the same reason

int *const p = 0; /* a const pointer */

int *foo() { 
  return p; /* OK, no error here */
}

What is returned in this case is a completely independent copy of the original pointer value. It does not matter whether p is const or not - making a copy of const value does not in any way violate its constness.

This is exactly what's done in your code sample - you are returning a copy of this's value. Why would you even care whether this is const or not?

like image 136
AnT Avatar answered Sep 30 '22 07:09

AnT


Unless the member function is const-qualified (e.g. T* func() const instead of just T* func()), this is of type T*.

this is not itself modifiable (so you can't assign something to this), but it's just a pointer to an object of type T like any other and can be used as such.

like image 45
James McNellis Avatar answered Sep 30 '22 07:09

James McNellis


AndreyT provided the explanation and here is the reference.

From standard docs 9.3.2.1 The this pointer,

In the body of a non-static (9.3) member function, the keyword this is an rvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*.

which explains the question that you asked and the comment you made to AndreyT.

Hope this one also helps.

like image 21
liaK Avatar answered Sep 30 '22 09:09

liaK