Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change 'this' pointer of an object to point different object

Tags:

c++

this

class C{
   //methods and properties
}

void C::some_method(C* b){
    delete this;
    this = b;     
}

This gives me follwing error when compiling:

error: lvalue required as left operand of assignment

My intention: Say there are objects a and b of class C. The contents of the class C can be very huge and field by field copying can be very costly. I want all the contents of 'a' to be replaced by 'b' in an economical way.

Will default copy constructor do the intended task?

I found something called 'move constructor' http://akrzemi1.wordpress.com/2011/08/11/move-constructor/

Perhaps, it might get the effect that I want.

like image 967
Utkrist Adhikari Avatar asked Aug 14 '13 09:08

Utkrist Adhikari


2 Answers

The this-pointer is an implicit pointer to the object in whose context you are working, you cannot reassign it.

According to Stroustrup's bible (The C++ Programming Language, 3rd edition I have) this is expressed as

C * const this

meaning you have a constant pointer to your class C, so the compiler will complain if you try to change it.

EDIT:

As I was corrected, the above mentioned expression does not describe this fully correctly, for this is actually an rvalue.

like image 100
bash.d Avatar answered Sep 30 '22 05:09

bash.d


You cannot change what this points to. I would also not know why you'd want to do this.

like image 27
Tony The Lion Avatar answered Sep 30 '22 05:09

Tony The Lion