使用构造函数时何时必须使用"this C++?

When do I have to use 'this' when using C++ constructors?

本文关键字:this C++ 何时必 构造函数      更新时间:2023-10-16
class Int {
    int n;
public:
    Int(int n) {
        this->n = n;
    }
};

class Int {
    int n;
public:
    Int(int n) : n(n){
    }
};

这两者之间的本质区别是什么,在创建给定类的新对象时何时应该使用 this 关键字?

最大的区别是第二种是推荐的方法,因为它避免了双重初始化属性。int是一个微不足道的情况,但你可以想象你可能有一些昂贵的结构,会被初始化两次:

Complicated(const HeavyObject& _h) : h(_h) {
  // h only initialized once
}
Complicated(const HeavyObject& _h) {
  // h already initialized with default constructor
  // Copy to object, potentially initializing all over again.
  this->h = _h;
}