我应该使用 "this" 关键字从成员函数内部访问类成员吗?

Should I use "this" keyword to access class members from inside member functions?

本文关键字:成员 内部 访问 函数 this 关键字 我应该      更新时间:2023-10-16
template <class T>
Vector<T>::Vector() : _size_(0){
    this->_capacity_ = 10;
    buffer = new T[this->_capacity_];
}
template <class T>
Vector<T>::Vector(unsigned int s) {
        this->_size_ = s;
        this->_capacity_ = _size_;
        this->buffer = new T[this->_capacity_];
        init(0, this->_size_);
}
template <class T>
Vector<T>::Vector(unsigned int s, const T &initial){
    this->_size_ = s;
    this->_capacity_ = s;   
    this->buffer = new T[this->_capacity_];
    init(0, s, initial);
}

我的代码经常使用 this 关键字。调用类中的成员函数而不是直接访问它而不使用 this 关键字是否被认为是一种良好做法?如果我总是调用成员函数来访问成员变量,是否会产生开销?C++实现有什么作用?

没有开销,因为代码是编译的。当您执行以下操作时:

this->_size = 5;

_size=5

编译器将它们视为相同并生成相同的代码。

如果你喜欢使用"这个",那就使用它。

我个人不喜欢它。

在构造函数中初始化成员的方式是错误的。应使用初始值设定项列表:

struct X {
  X() : a(1), b(2), c(3) {}
  int a, b, c;
};

否则,该值必须默认初始化,然后重置。

访问非虚拟成员函数的成本很难计算,因为它取决于内联。如果它是内联的,则开销是空闲的。这很可能是简单的获取/设置者。

对于虚拟成员函数,它取决于编译器在编译时可能提升虚拟调用的能力,但您应该假设会有开销。