C++ this Pointer: Chaining, const Methods, Lambdas, and CRTP
이 글의 핵심
this points to the current object in non-static member functions. Learn name disambiguation, returning *this, self-assignment, and lifetime pitfalls with [this] lambdas.
What is this?
this is a pointer to the current object in non-static member functions. It is passed implicitly and can be used explicitly when needed.
class MyClass {
int value;
public:
void setValue(int value) {
this->value = value;
}
};
Why it matters:
- Disambiguate members from parameters
- Method chaining (
return *this) - Self-assignment checks in
operator= - Passing
thisto callbacks/registrations
this type and cv-qualifiers
In const member functions, this is const T* (pointer to const). Ref-qualified members (&/&&) split overloads for lvalue vs rvalue *this.
Conceptual lowering
Non-static member functions conceptually take T* this as a hidden parameter: obj.f() ↔ f(&obj, ...).
Basic usage
Constructor initializer lists often use this->x = x style or member init lists—prefer member init lists when possible.
Practical examples
Method chaining
class Builder {
std::string data;
public:
Builder& append(const std::string& s) {
data += s;
return *this;
}
};
Self-assignment guard
Array& operator=(const Array& other) {
if (this != &other) {
// ...
}
return *this;
}
Callbacks passing this
Use care with asynchronous lifetimes.
static members
No this in static member functions.
Lambdas and this
[this]— copies the pointer; lifetime risk if stored beyond the object.[*this](C++17) — copies the object (watch cost and slicing).[=]in member functions may implicitly capturethisin ways that surprise readers—prefer explicit[this]or[*this].
Templates and dependent names
In derived class templates, this->member can help name lookup for members from dependent bases.
Common mistakes
- Async callbacks capturing
[this]after destruction - Using
thisinstaticfunctions - Assuming polymorphic calls during base construction/destruction
FAQ
Full answers: what this is, when to use it, no this in static functions, const methods, lambda captures, ctor/dtor caveats.
Resources: C++ Primer, Effective C++, cppreference.
Related posts (internal links)
- static members
- mutable keyword
- nullptr
Practical tips
Debugging
- Warnings; minimal repro.
Performance
thisitself is cheap; watch indirect calls and cache behavior.
Code review
- Audit
[this]lifetimes.
Practical checklist
Before coding
- Lifetime clear for callbacks?
While coding
- UB avoided?
During review
- Async safe?
Keywords (search)
C++, this, pointer, member, class
Related posts
- static members
- struct vs class
- Initialization order
- mutable
- nullptr vs NULL