Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it allowed to assign to a dereferenced this (*this)?

Tags:

c++

I'm currently refreshing my C++ skills and was wondering if it is possible to assign something to *this. I know assigning to this is forbidden, but can't find the same information for my case.

An example:

class Foo {
  int x;
public:
  Foo(int x) : x(x) {}
  Foo incr() { return Foo(x+1); }
  void incr_() { (*this) = incr(); }
};

Edit: corrected incr()'s return type from void to Foo.

like image 370
Kolja Avatar asked Oct 15 '10 17:10

Kolja


3 Answers

Yes, it is allowed, and it actually invokes your class' assignment operator.

like image 88
Etienne de Martel Avatar answered Sep 18 '22 18:09

Etienne de Martel


void incr() { return Foo(x+1); }

This is invalid. You cannot return a Foo object from a function having void return type.

void incr_() { 

   (*this) = incr(); // This invokes Foo& operator = (const Foo& ) (compiler synthesized)
}

This is fine.

like image 34
Prasoon Saurav Avatar answered Sep 17 '22 18:09

Prasoon Saurav


Yes, it works. And *this = x is just syntactic sugar for operator=(x).

like image 33
fredoverflow Avatar answered Sep 19 '22 18:09

fredoverflow