I was wondering if it was a good practice to use ‘this’ in C++. At first I thought I should be because that way you make obvious that the thing you are referring is a member of the current class but sometimes you end with code like:
Document::Document(QWidget *parent) : QWidget(parent)
{
this->file = 0;
this->layout = new QGridLayout(this);
this->layout->setSpacing(2);
this->layout->setMargin(0);
this->setLayout(this.layout);
this->textArea = new QTextEdit(this);
this->textArea->setLineWrapMode(QTextEdit::NoWrap);
this->textArea->setAcceptDrops(true);
this->textArea->setAcceptRichText(true);
this->textArea->setUndoRedoEnabled(true);
this->textArea->setFont(QFont("Mono" , 11));
this->layout->addWidget(this->textArea);
this->textArea->show();
this->textArea->setFocus();
}
I thing this would look a lot better without all the ‘this’ specially when it is used like this->layout->addWidget(this.textArea);. And I think the code should use the same style in most cases to make it easier to be read so, should I use ‘this’ just when it is necessary or is it a good practice to use it to make clear that you are referencing a member of the same class.
There’s no single answer to this. It depends on the context, and it depends on who you ask.
Some people use
thisall the time. Some never use it. Some instead rename all member variables with a special prefix (mFileinstead offile).I prefer to only use the
thisprefix when it’s necessary to avoid ambiguity.In well written code, it is usually obvious whether you’re referring to a local or a member variable, and so
thisdoesn’t really do much. But sometimes it can be hard for the reader to determine if a variable is a class member or not. Thenthisis a good way to clarify.