C++中this到底指针是啥?有啥用?

Admin·5/30/2025·0 views
C++

this 指针是C++类中每个非静态成员函数都隐式拥有的一个指针,指向当前对象自身。 它的类型是 ClassName* const,即“指向当前类类型的常量指针”。

常用场景

1. 区分成员变量和参数

当成员变量和函数参数同名时,常用 this-> 区分:

class Person {
    std::string name;
public:
    void setName(const std::string& name) {
        this->name = name; // this->name 是成员变量,name 是参数
    }

};

吐槽:一般来说我们都会在函数参数前加上p

2. 在成员函数中返回当前对象

常用于链式调用(返回 this)

class Counter {
    int value;
public:
    Counter& increment() {
        ++value;
        return *this; // 返回当前对象的引用
    }
};

Counter c;
c.increment().increment(); // 支持链式调用

3. 作为成员函数指针调用的对象

std::bind(&ClassName::func, this, arg1, arg2)

这里 this 保证了成员函数 func 是在当前对象上调用的。

4. 在构造函数或成员函数中传递当前对象

class Widget {
public:
    void registerSelf() {
        SomeManager::registerWidget(this); // 传递当前对象指针
    }
};

5. 防止自赋值

在重载赋值运算符时,常用 this 判断自赋值:

MyClass& operator=(const MyClass& other) {
    if (this == &other) return *this; // 检查是否自赋值
    // ...赋值逻辑...
    return *this;
}

6. 智能指针获取自身

有时需要获取当前对象的 shared_ptr,可以用 shared_from_this(),但前提是继承自 std::enable_shared_from_this,本质上也是用 this。

Comments (0)