20

This macro can be defined in some global header, or better, as a compiler command line parameter:

#define me (*this)

And some usage example:

some_header.h:

inline void Update()
{
    /* ... */
}

main.cpp:

#include "some_header.h"

class A {
public:
    void SetX(int x)
    {
        me.x = x;   
        me.Update(); 
    }

    void SomeOtherFunction()
    {
        ::Update();
    }

    /*
        100 or more lines
        ... 
    */

    void Update()
    {
        // ... 
    }

    int x;  
};

So in a class method when I access a class member, I am always using me, and when accessing a global identifier I always use ::. This gives the reader which is not familiar with the code (probably myself after a few months) localized information of what is accessed without the need to look somewhere else. I want to define me because I find using this-> everywhere too noisy and ugly. But can #define me (*this) be considered a good C++ practice? Are there some practical problematic points with the me macro? And if you as C++ programmer will be the reader of some code using the me macro, would you like it or not?

Edit: Because many people arguing not specificaly contra using me, but generaly contra explicit this. I think it may not be clear what are benefits of "explicit this everywhere".

What are benefits of "explicit this everywhere"?

  • As a reader of the code you have certainty what is accessed and you can concentrate on different things than verify - in some distant code - that is really accessed what you think is accessed.
  • You can use search function more specifically. Search "this->x" can give you more wanted results than only search "x"
  • When you are deleting or renaming some member, compiler reliably notifies you at places where is this member used. (Some global function can have same name and exist chance you can introduce error if you are not using explicit this).
  • When you are refactoring code and making non-member function from member (to make better encapsulation) explicit this shows you place which you must edit and you can easily replace this with pointer to instance of class given as non-member function parameter
  • Generally when you are changing code, there are more posibilities to errors when you are not using explicit this than when you are use explicit this everywhere.
  • Explicit this is less noisy than explicit „m_“ when you are acessing member from outside (object.member vs object.m_member) (thanks to @Kaz to spot this point)
  • Explicit this solves problem universaly for all members – attributes and methods, whereas „m_“ or other prefix is practicaly usable only for attributes.

I would like to polish and extend this list, tell me if you know about other advantages and use cases for explicit this everywhere.

user3123061
  • 1,609
  • 1
  • 15
  • 17
  • 3
    You should avoid having function arguments and members with the same name, as well as avoiding explicit "this". – pjc50 Jul 14 '14 at 09:32
  • 4
    Reminds me of my boss' VB code. Me Me Me everywhere. Sounds selfish. :p Anyway, the answers so far say it all. – MetalMikester Jul 14 '14 at 12:05
  • 20
    It is a wonderful idea! And for those who come from a Python background, why not `#define self (*this)` ? You can even *mix both macros* and have some files imitating VB and others Python. :) – logc Jul 14 '14 at 13:38
  • 11
    Why not just go all out, and do: `#include "vb.h"`, `#Include pascal.h`, or `#include FOTRAN.h` and have the next person to touch your code submit it to [TDWTF](http://thedailywtf.com/). – Dan Is Fiddling By Firelight Jul 14 '14 at 15:10
  • Objective-C and Python coders would unanimously prefer `self` instead of `me`. – glampert Jul 14 '14 at 18:26
  • 4
    Oh please, just no. You could save yourself some trouble by just declaring attributes as `me_x`. – Gort the Robot Jul 14 '14 at 18:39
  • 1
    @StevenBurnap: Exactly. And then the compiler will even point out places you forgot the `me_` (or `m_` as is more widely seen) – Ben Voigt Jul 14 '14 at 23:08
  • 2
    And people still wish to know way so many programmers felt the need to move to Java/C# to escape from the world of unmaintainable C++ cope..... – Ian Jul 15 '14 at 14:32
  • The problem with language aliasing is that, it could start with one or two "reasonable" aliases, but could lead to this: http://stackoverflow.com/a/1466303/1609356 – Manu343726 Jul 15 '14 at 15:09
  • 1
    As an alternative comment--I think the pattern of identifying members with this. is pretty bad. I really don't even like using m_, the reason is that it can be wrong. One refactor where you forget to change the name can cause a LOT more work than just letting your tools do their job. (I don't know about C++ IDEs, but in Java/Eclipse members, statics and locals can easily be differentiated at least 3 ways--by color/font, hovering and ctrl-clicking. Perhaps your team would be better served if you spent time looking into more appropriate tools? – Bill K Jul 15 '14 at 20:57
  • 1
    @StevenBurnap Uh, if you call attributes `me_` then you have the problem of `me_foo = other_object.me_foo`. – Kaz Jul 16 '14 at 00:17
  • Depends. Are you a pirate? – congusbongus Jul 16 '14 at 02:51
  • @Ian guess you've never seen unmaintainable Java/C# code. I have and it is no different from unmaintainable code in any language. The language doesn't make the code unmaintainable: the coder does. – cup Jul 16 '14 at 11:38
  • @cup, But C/C++ gives the coder so much more power to redefine the language, at least in Java/C# when I see what looks like the “while” keyword, I know it is. – Ian Jul 16 '14 at 13:12
  • *(...) tell me if you know about other advantages and use cases for explicit this everywhere.* – see [What is the advantage of having this/self pointer mandatory explicit?](http://stackoverflow.com/q/910020/95735) – Piotr Dobrogost Jun 16 '15 at 12:03

5 Answers5

90

No, it is not.

Mind the programmer who will maintain your code several years from now long after you've left for greener pastures and follow common conventions of the language you use. In C++, you almost never have to write this, because the class is included in symbol resolution order and when a symbol is found in class scope, this-> is implied. So just don't write it like everybody does.

If you often get confused which symbols come from class scope, the usual approach is using common naming pattern for members (fields and sometimes private methods; I haven't seen it used for public methods). Common ones include suffixing with _ or prefixing with m_ or m.

Jan Hudec
  • 18,250
  • 1
  • 39
  • 62
  • 13
    *"In C++, you almost never have to write this"* that's a totally unrelated convention to the question. Some people (like me) prefer to write `this` to explicitly make it clear that the variable is not local to the method. The question here is about whether the macro `me` should exist, not whether `this` is something that should be used. – user541686 Jul 14 '14 at 20:43
  • 8
    @Mehrdad: Because the OP explicitly says he is using `me.` instead of `this->`. Since there is no need for `this->` there is no need for `me.` and thus no need for the macro. – Martin York Jul 14 '14 at 21:36
  • 12
    @LokiAstari: Nothing in the question even remotely hints at the OP wondering whether `this->` "is necessary". In fact, the OP says he is using `this->` in spite of the fact that it's not necessary. The question is about whether `me.` should be used **instead of** `this->`, which this answer doesn't actually answer. – user541686 Jul 15 '14 at 00:51
  • 4
    @Mehrdad: But only putting yes or no makes a very boring answer. Thus explanations are usually quite useful in explaining how the answer is reached (is encoraged by [How to answer](http://programmers.stackexchange.com/help/how-to-answer) ). The conclusion is not to use because the OP has the wrong attitude to start with about using `this` and thus a discussion on that point is required to achieve a fully balanced conclusion. – Martin York Jul 15 '14 at 01:12
  • 1
    +1 for explaining why, instead of just saying "No, it's a bad practice." – user253751 Jul 15 '14 at 01:18
42

So, you want to create a new language. Then do so, and do not cripple C++.

There are several reasons not to do it:

  1. Every normal coding standard will suggest to avoid macros (here is why)
  2. It is harder to maintain code with such macros. Everyone programming in C++ knows what this is, and by adding such macro, you are actually adding a new keyword. What if everyone introduces something they like? What would code look like?
  3. You shouldn't use (*this). or this-> at all, except in some special cases (see this answer and search for "this->")

Your code is not different from #define R return, which I saw in the actual code. Reason? Less typing!


Going slightly off topic, but here I am going to expand on point 3 (do not use (*this). or this-> in a class).

First of all, (*this). or this-> are used to access member variables or functions of the the object. Using it is meaningless and means more typing. Also, reading such code is more difficult, because there is more text. That means harder maintenance.

So, what are the cases where you have to use this->?

(a) Unfortunate pick of the argument's name.

In this example, this-> is required, since the argument has the same name as the member variable :

struct A {
  int v;
  void foo( int v ) {
    this->v =v;
  }
};

(b) When dealing with templates and inheritance (see this)

This example will fail to compile, because the compiler doesn't know which variable named v to access.

template< typename T >
struct A {
  A(const T& vValue):v(vValue){}

  T v;
};

template< typename T >
struct B : A<T>
{
    B(const T& vValue):A<T>(vValue){}

    void foo( const T & newV ) {
      v = newV;
    }
};
BЈовић
  • 13,981
  • 8
  • 61
  • 81
  • 1
    "So, you want to create a new language. Then do so, and do not cripple c++." - I disagree. A major strength of C and C++ is their flexibility. The OP is not crippling C++, just utilizing its flexibility in a particular way to make it easier for him or her to code. – user253751 Jul 15 '14 at 07:50
  • 2
    @immibis Right. What is easier for him, is harder for everybody else. When you work in a team, putting such nonsenses in the code will not make you very favorable. – BЈовић Jul 15 '14 at 07:56
  • 2
    Your answer is not different from "defines are evil". – Mr Lister Jul 15 '14 at 08:34
  • 7
    @MrLister My answer is "stupid defines are evil". The macro in the question is stupid to use, and as I showed, not needed at all. The code is good and even better without `*this.` and `this->` – BЈовић Jul 15 '14 at 08:51
  • You just lost my up vote when I read case 3. `*this` has very good uses. – Thomas Eding Jul 15 '14 at 16:09
  • refuting point by point, in reverse for fun: 3, as @ThomasEding said your argument is over-broad at best. 2. who is this everybody and where does he say what he knows. 1. the reference is about the specific case of function macros which does not apply to this case. – hildred Jul 15 '14 at 18:29
  • @ThomasEding In BЈовић's defense, he did say `*this.` (with a period) rather than just `*this` in general. – Mr Lister Jul 15 '14 at 18:57
  • @ThomasEding Please, next time provide a link to Q&A showing good uses of *this, as I am always eager to learn something new. And do not try to protect the nonsense in the question. Using this-> everywhere is just plain stupid – BЈовић Jul 15 '14 at 23:22
  • @hildred See edits. Under "everybody" I meant people programming in c++ (obviously). The reference tells when this-> has to be used (some special case with templates, when a templated class inherits a class). – BЈовић Jul 15 '14 at 23:29
  • BЈовић, whenever any one says 'everyone says' or 'everyone knows' (even in the more limited scope you have defined in your revision), they are at best making an over-broad statement (you assert something that neither user3123061 who gets payed to program in c++ nor I know as something that everyone knows) or are more likely wrong. So I stand by my refutation of point 2. Further your argument in support of point 3 points out a set of exceptions, where my argument is even if I were to accept your style arguments against *this that you missed some of the exceptions like (continued ...) – hildred Jul 16 '14 at 01:06
  • (continued) casting to *void for use as aux data for a callback. And you still did not support point 1. – hildred Jul 16 '14 at 01:08
  • @hildred I have nothing more to add to the point 3, except for the latest edit. As for the point 2, I feel sorry for whoever is unfortunate enough to have to read your code. – BЈовић Jul 16 '14 at 07:30
  • *"Using `this->` everywhere is just plain stupid"* uh, no, it's pretty smart. I could just as well argue *not* doing so is stupid. It lets you avoid screwing with instance variable names by prefixing them with `m_` or `_` or whatever just because you're too lazy to type `this->`, making the code that much more readable. – user541686 Jul 16 '14 at 08:52
  • 1
    @Mehrdad Are people still adding prefixes and suffixes to member variables? I thought that was "fixed" with books like [Clean Code](http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882). `this->` is as useful as `auto` in pre-c++11. In other words, it just increases code noise. – BЈовић Jul 16 '14 at 09:05
  • @BЈовић: How else are you supposed to distinguish between member and local variables? Either you change the naming convention, or you use `this->`. I don't mean for the compiler's sake, I mean for the sanity of the next poor programmer who has to read your code. If you don't write `this->` then you're going to waste the people's valuable time when they go hunting for the scope of the variable. That's at least 5 seconds of thinking that could be turned into 1 second, with 4 more left to spend on more important things. Multiplied by the number of times your code has to be read. – user541686 Jul 16 '14 at 10:08
  • Not to mention that using `this` actually helps you write your code *faster* because the IDE can display a drop-down listing all the member variables, from which you can easily select a member without typing most of its name at all. So it's not even good from a coding efficiency standpoint. – user541686 Jul 16 '14 at 10:11
  • @Mehrdad Obviously, that is a personal preference. I surely hope your classes declarations and functions do not stretch over pages, so people wouldn't have to think long whether they access a local variable, or member variable. – BЈовић Jul 16 '14 at 11:28
  • @BЈовић: Pages? It's not a question of thinking "long", it's a question of not having to think *at all*. When `this->` is there--and you have a habit of putting it in there whenever it's possible--then you are immediately 100% certain the variable is an instance field. It requires no thinking whatsoever, so it's not distracting. But when that's not the case, then you have to think. Whether that's 5 seconds or 30 seconds is a different issue, the point is it still takes up unnecessary mental resources regardless, without any benefit in terms of development speed either as I mentioned earlier. – user541686 Jul 16 '14 at 11:34
  • As for 2.: If everyone got to add whatever syntax they like, the language would probably look a bit like Ruby or Perl. :) And though it might technically be correct to say that "everyone knows" is overbroad, and some people definitely don't understand the intricacies of `this`, everyone who programs in C++ *should know* (at least roughly) what `this` means. `#define me (*this)` only helps the people who don't -- those being the very people that *shouldn't* be messing with the code, IMO. – cHao Jul 23 '14 at 15:36
26

I suggest not to do this. This gives a reader which is not familiar with your macro a big "WTF" whenever he sees this. Code does not get more readable when inventing "new conventions" over the generally accepted ones without any real need.

using this-> everywhere is too noisy and ugly

That may seem so to you, maybe because you did a lot of programming in languages using the keyword me (Visual Basic, I guess?). But in fact it is just a matter of becoming accustomed to it - this-> is pretty short, and I think most of experienced C++ programmers will disagree with your opinion. And in the case above, neither the use of this-> or the use of me is appropriate - you get the smallest amount of clutter by leaving those keywords out when accessing data members inside of member functions .

If you want your private member variables to be distinguished from local ones, add something link m_ as a prefix, or an underscore as a suffix to them (but as you can see here, even this convention is "too noisy" for many people).

Doc Brown
  • 199,015
  • 33
  • 367
  • 565
  • 12
    `_` should be _suffixed_; as prefix it is reserved for internal symbols of standard libraries and vendor extensions. – Jan Hudec Jul 14 '14 at 07:20
  • 4
    @JanHudec Only if it starts with `__` (two underscores) or an underscore followed by a capital letter. A single underscore followed by a lower case letter is fine, as long as it's not in the global namespace. – Eric Finn Jul 14 '14 at 13:33
  • 1
    @EricFinn: I combined the two rules to one. Two underscores or underscore followed by capital letter is for internal symbols and single underscore followed by lower case letter is for system-specific extensions. Applications should not use either. – Jan Hudec Jul 14 '14 at 14:36
  • @JanHudec Wasn't aware of the rule for system-specific extensions. I'll leave my previous comment to provide some context for your comment, though. – Eric Finn Jul 14 '14 at 14:38
  • 2
    @JanHudec: Lowercase is for system-specific extensions? Could you post a reference to the part of the C++ standard that indicates this? – user541686 Jul 14 '14 at 20:45
  • Unneeded prefixes are annoying regardless of what form they take. – candied_orange Jan 01 '18 at 06:58
18

Please don't do it! I am trying to cope with a large code base where macros are all over the place to save typing. The bad thing about redefining this to me is that the preprocessor will replace it everywhere even where this is not in scope/does not apply, for instance a stand-alone function, your fellow colleage might have a local variable called me somewhere else... (s)he won't be happy debugging... You end up having macros which you can't use in all scopes.

truschival
  • 281
  • 1
  • 2
6

NO!

Just imagine the confusion that will occur if somebody #include's that header, not knowing your trick, and elsewhere in their file they have a variable or function called "me". They would be horribly confused by whatever inscrutable error message would be printed.

Larry Gritz
  • 541
  • 3
  • 5
  • In practice, they're quite likely to mouse-over "me" with their IDE and see the definition. – user253751 Jul 16 '14 at 02:30
  • 2
    @immibis: In practice, though, they're also likely to say something like "who wrote this crap?". :P – cHao Jul 16 '14 at 13:05
  • @immibis: most of the top coders I work with don't use the mouse - it is too slow. – JBRWilkinson Jul 16 '14 at 22:56
  • Indeed: shoving this in a header is the actual problem. If you use it in your cpp file I don't see a problem at all. If we had pragma push as standard I'd be advising how to do this in a header, but we don't. Repeat after me. #defines are global. – Joshua Dec 31 '17 at 20:02