-1

I've googled the keyword "this", and most of them gave the similar examples.

http://www.geeksforgeeks.org/this-pointer-in-c/ http://www.tutorialspoint.com/cplusplus/cpp_this_pointer.htm

When I ran into this,

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

It just doesn't make sense. What does "this" point to? If it points to 'token', how does it do that?

  • 2
    possible duplicate http://stackoverflow.com/questions/6779645/use-of-this-keyword-in-c – Rao Dec 01 '15 at 03:52
  • 3
    Try reading a [book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of googling random keywords. – user657267 Dec 01 '15 at 03:52
  • You're right, that doesn't make sense. `this == nullptr` cannot be true in a valid program, so an optimizing compiler will most likely simply throw it away. – Ben Voigt Dec 01 '15 at 03:57
  • @Rao Not a duplicate; that question asks why people use it when it's redundant, this question asks *what it does*. – user253751 Dec 01 '15 at 03:58
  • @immibis which could be answered by "nothing, since it's redundant" ... – M.M Dec 01 '15 at 04:07
  • @M.M. `this` most definitely does not do nothing. – user253751 Dec 01 '15 at 04:18

2 Answers2

3

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.

  • "if statement above is seeing if the instance of the object is equal to a null reference" - this is impossible, unless the program has already triggered undefined behaviour – M.M Dec 01 '15 at 04:04
  • @M.M Nonetheless, that is exactly what that `if` statement is doing. – user253751 Dec 01 '15 at 04:20
2

Checking this with NULL in c++ is discouraged. this could be NULL when the method is invoked on a NULL pointer to the class. An example:

Token* token = nullptr;
token->~Token();

The code really should check if token is NULL in the first place, instead of checking NULL in the destructor.

Token* token = nullptr;
if (token)
  token->~Token();

This link explains your question: http://www.viva64.com/en/b/0226/

How Google and Foxit fixed this issue in pdfium:

https://bugs.chromium.org/p/pdfium/issues/detail?id=4 https://groups.google.com/forum/#!topic/pdfium/8mTxtmle4ok

user3701366
  • 474
  • 1
  • 5
  • 7