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
vsobject.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.
#define self (*this)
? You can even mix both macros and have some files imitating VB and others Python. :)#include "vb.h"
,#Include pascal.h
, or#include FOTRAN.h
and have the next person to touch your code submit it to TDWTF.me_x
.