Waqas Ahmad
Waqas Ahmad

Reputation: 43

C++ - assignment to 'this' anachronism

I was given this code and asked to state what was wrong with it, and how to fix it. The code gives me an error something like c++ assignment to this anachronism, and I'm not sure what this means.

I am new in C++ and I don't know what to do here. Please help. Here is the code in question:

class SELF
{
  private:
    SELF * me;
  public:
     SELF()
     {
          this = me;
     }
 };

How can I assign the value

Upvotes: 2

Views: 3835

Answers (1)

Omnifarious
Omnifarious

Reputation: 56048

This is a C++ construct that was removed from the language over 30 years ago. It's from the early days of cfront in mid-80s and you could still find compilers that did things this way until the very early 90s. It's been replaced with operator new. I wrote some of my very first C++ code (a complex class for a Mandlebrot set generator) on a compiler that worked this way.

You didn't originally give enough context here to know how to fix the problem in this case. There is no trivial transformation that can be prescriptively applied to all situations.

The construct was initially created so that you could allocate memory for the object in the constructor. If you assigned to this in the constructor, the compiler wouldn't allocate memory for your object when you created it, it would assume that you did it yourself in the constructor.

In a comment, you stated that this was directly copied from a university assignment, and I bet not even your professor is aware of this old construct, the solution is probably to simply say me = this; instead of this = me;.

But the reason your compiler is calling this an 'anachronism' is that it is.

For anybody who is interested in the history, the original construct can be seen on page 42 of the manual for cfront version 'E'.

Upvotes: 13

Related Questions