Use of "This" Keyword in C++

Is it wise to use the `this` keyword in C?

Using this in any fashion you want is totally valid C.

What you have to ask yourself, by the way these apply to any C++ reserved words like class, final etc, is :

  • Do I use a program that highlights this as a keyword conveing the wrong message ? e.g. Visual Studio highlights this even when you're in a .c file so some confusion may arise.
  • Do I plan to promote my code to C++ in the future ? In such a case you'll have some extra work to do that could be avoided.
  • Does my code interact with C++ ? This is not a problem per se but you have to bear in mind that your code will interact with C++ programmers as well. And you don't won't to confuse people that may not be aware of C in great detail (even though someone may say it's their duty do be aware of what they're doing when reading another language).

Since this is something that can be avoided I find using it immoral but not incorrect.

I'm not saying you have to study C++ prior to writing C, but once you know something, it's a good practice to make good use of it.

A subtle problem you may cause is to make your code 'uncallable' from C++ for example a

#define this some_definition

in a C header file that is later included from C++ may have weird effects to your code.

Using `this` keyword in plain C

No, you can't do that since this is a reserved word in C++. It cannot be used as the name of an ordinary argument.

You can remove the name from the header and keep it in the C file, but that of course means making the header slightly worse since it no longer contains the hint what that argument is meant for.

Use of this keyword in C++

Yes, it is not required and is usually omitted. It might be required for accessing variables after they have been overridden in the scope though:

Person::Person() {
int age;
this->age = 1;
}

Also, this:

Person::Person(int _age) {
age = _age;
}

It is pretty bad style; if you need an initializer with the same name use this notation:

Person::Person(int age) : age(age) {}

More info here: https://en.cppreference.com/w/cpp/language/initializer_list

Implementation restrictions of this keyword in C++, as it relates to dangerous but functional example

So I reached out to Stephan Lavavej (Stephan's website), who maintains the Standard Library implementation for Microsoft, with this question. I will post his answer below. I do want to point out that user HAL9000 was essentially right with his answer, but since Stephan's was so thorough, I'll post it, and eventually designate it as the official answer(it's hard to get more official than the words of someone who actually maintains a Big 3 implementation of the Standard). If you find this answer informative, HAL9000's answer has a visual example to reinforce the idea.

Stephan's Words:

You shouldn't think of the "this" pointer as being stored within an object. The implicit parameter mental model is the most accurate one.
When a function x() calls a member function Meow::y() on a Meow object m, x() has to know the address of m already. It might be a local variable (x() knows where all of its local variables live on the stack), it might be a dereferenced pointer (if m is *ptr, ptr points to m), it might be passed via reference (references are not pointers, but they effectively have the same location information as pointers), it might be an element on an array (if m is arr[idx], then arr + idx points to m), etc. So Meow::y() will be implicitly passed the address of m, which becomes "this" within the member function.

Crucially, if you have a struct that contains plain old data (e.g. a bunch of ints) and you swap the contents of two structs, the objects don't change identity - only their contents. If I take all of your stuff in your house and swap it with the stuff within someone else's house, the locations of the houses are unchanged. (In C++, objects can't migrate from one memory address to another - the most you can do is create a separate object, move all the stuff, tell anyone who cares about the old location to instead point to the new location, and then destroy the empty shell of the original object - that's move semantics, basically.)

Because "this" isn't actually stored anywhere, it has zero cost, which is useful to know. (This is outside virtual member functions, which do make objects pay a vptr cost, but that's much more advanced.)

Hope this helps,
STL

Object oriented C programming - equivalent of 'this' keyword?

No. this keyword in C++ is a reference to the object at hand, and is actually explicitly passed to the member functions at the ABI level. Explicitly passing a pointer to the object (as the first parameter) in functions is the best equivalent in C. Note that this means

struct foo {
int value;
int (*func)(struct foo *, int);
};

void foo_bar(struct foo *f, int value)
{
f->value = value;
}

i.e. the pointer to the object is passed as the first parameter, rather than the structure itself. This makes it explicit that the object is passed by reference, and makes understanding and maintaining such code easier.


It is not sane to expect features seen in one programming language to be valid in some other programming language, even if the two are related somehow.

You see, each programming language has their own approach to problem solving, their own paradigm. Because there is no universal best paradigm possible, problems are best solved using a programming language that has the most applicable/efficient/useful paradigm. For example, you don't write a C++ program to expedite common command-line tasks; you use a shell script or other simple scripting language instead.

As a programmer, having the ability to switch from one programming language paradigm to another means you have the ability to look at a problem from different viewpoints. Looking at current software projects, the most robust, vital, and efficient ones are written by programmers who have that ability.

This is why I stated, above, that it is not sane to expect the features or paradigm of one programming language to be portable to others. You should not do that, because it is equivalent to having a single tool, and looking at all problems as if your tool at hand is the only possible tool in solving them. (If all you have is a hammer, all problems start looking like nails.) Learning, and especially learning to accept, the different paradigms in different programming languages, makes for a better programmer, better problem-solver.

When should you use the this keyword in C++?

While this is a totally subjective question, I think the general C++ community prefers not to have this->. Its cluttering, and entirely not needed.

Some people use it to differentiate between member variables and parameters. A much more common practice is to just prefix your member variables with something, like a single underscore or an m, or m_, etc.

That is much easier to read, in my opinion. If you need this-> to differentiate between variables, you're doing it wrong. Either change the parameter name (from x to newX) or have a member variable naming convention.

Consistency is preferred, so instead of forcing this-> on yourself for the few cases you need to differentiate (note in initializer lists this is completely well-defined: x(x), where the member x is initialized by the parameter x), just get better variable names.

This leaves the only time I use this: when I actually need the address of the instance, for whatever reason.

this keyword, what does this mean?

this is just a pointer to a current object of the class to which the function is a member of. Its more of a hidden parameter that is passed to every NON-STATIC method of a c++ class. It simply points to a specific instance of a class along with all the data that the object has. So for your example:

Token::~Token() {
if(this == nullptr) { return; }
.... }

This is just pointing to the object of the Token classes' destructor function.

if(this == nullptr) { return; }

To be even more specific, the if statement above is seeing if the instance of the object is equal to a null reference.

Is it possible to force the use of the this keyword in C++?

This is a circular problem. You want the compiler to error out and inform you when you're accessing a class member without prefixing this->, so that you cannot be accidentally referring to a local variable or function argument instead … but for that exact same reason, how is the compiler supposed to know that you really intended to access the member? And, if you didn't, how would you access the local variables or function arguments?

C++ is simply not designed this way. Some languages, such as PHP, require that you must use this to access members and any other access is treated as an attempt to read local-scope variables (whether they exist or not), but C++ does not have that. And there is no compiler switch to make it happen. If this worries you, avoid re-using the names of variables!

In short, this is a non-problem that cannot be solved.

Problem about usage of this keyword in C++

this is a pointer, as others have said, but it's much better and more correct to use the base initializer list:

class Monitor
{
int rate;
public:
Monitor(int rate) : rate(rate) { }
};

That way, Monitor::rate gets initialized to the right value, rather than first default-initalized and then assigned. For more general member objects this may in fact be the only legitimate way to initialize them.



Related Topics



Leave a reply



Submit