mirror of
https://github.com/Light-City/CPlusPlusThings.git
synced 2026-10-29 03:14:06 +08:00
- const README: rewrite the space-saving claim per issue #5 follow-ups (constant-expression const vs #define immediates; which const qualify as constant expressions) - const README: fix the class-section diagnosis per issue #338 (overload resolution picks the const overload; the restriction only surfaces once that overload is removed) - sizeof README: virtual-inheritance result is compiler-dependent (GCC merges vbptr+vfptr -> 16, MSVC keeps them separate -> 32) #246 - static README: new section on internal linkage / access restriction with anonymous-namespace comparison #142 - 10-day practice: full problem list table + fixed day links #136 - new design_pattern/singleton/singleton_default.hpp: reusable thread-safe CRTP singleton template, compile+concurrency tested #303
This commit is contained in:
@@ -1,10 +1,12 @@
|
||||
# this指针那些事
|
||||
> 本文档由 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/this/) 同步生成,网站版本含多语言与更新排版。
|
||||
|
||||
# C++ this 指针
|
||||
|
||||
## 关于作者
|
||||
|
||||
微信公众号:
|
||||
|
||||

|
||||

|
||||
|
||||
## 1.this指针
|
||||
|
||||
@@ -74,16 +76,16 @@ int main(){
|
||||
|
||||
为了验证this指针是哪一个,现在在`add_age`处添加断点,运行后如下:
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
会发现编译器自动为我们加上`A* const`,而不是`A const *this`!
|
||||
|
||||
紧接着,上述还有个常函数,那么我们在对`get_age`添加断点,如下:
|
||||
|
||||

|
||||

|
||||
|
||||
会发现编译器把上述的this,变为`const A* const`,这个大家也能想到,因为这个函数是const函数,那么针对const函数,它只能访问const变量与const函数,不能修改其他变量的值,所以需要一个this指向不能修改的变量,那就是`const A*`,又由于本身this是`const`指针,所以就为`const A* const`!
|
||||
|
||||
总结:this在成员函数的开始执行前构造,在成员的执行结束后清除。上述的get_age函数会被解析成`get_age(const A * const this)`,`add_age`函数会被解析成`add_age(A* const this,int a)`。在C++中类和结构是只有一个区别的:类的成员默认是private,而结构是public。this是类的指针,如果换成结构,那this就是结构的指针了。
|
||||
总结:this在成员函数的开始执行前构造,在成员的执行结束后清除。上述的get_age函数会被解析成`get_age(const A * const this)`,`add_age`函数会被解析成`add_age(A* const this,int a)`。在C++中类和结构是只有一个区别的:类的成员默认是private,而结构是public。this是类的指针,如果换成结构,那this就是结构的指针了。
|
||||
Reference in New Issue
Block a user