我应该使用 "this" 关键字从成员函数内部访问类成员吗?
Should I use "this" keyword to access class members from inside member functions?
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;
};
否则,该值必须默认初始化,然后重置。
访问非虚拟成员函数的成本很难计算,因为它取决于内联。如果它是内联的,则开销是空闲的。这很可能是简单的获取/设置者。
对于虚拟成员函数,它取决于编译器在编译时可能提升虚拟调用的能力,但您应该假设会有开销。
相关文章:
- 将函数类成员映射到类本身内部
- 如何在类内部使用和访问静态指针到成员值s_ptm?
- 是否允许分配器构造和销毁成员函数从内部逻辑引发异常?
- 访问说明符(私有/公共/受保护)如何在内部工作(限制成员访问)?
- 返回自身内部的双重嵌套类的成员函数,该类继承自从自身继承的类
- 指向C++中成员的指针如何在内部工作?
- 我如何从循环内部使用迭代器的函数内部的getter中检索特定的成员
- 结构内部的结构:"对非静态成员的非法引用"错误
- 从对象成员函数内部删除操作的技术 /设计模式
- 班级成员在C Lambdas中捕获内部构造函数
- 在成员函数内部调用成员函数
- 如何在类构造函数内部对同一类的成员函数启动pthread
- 类(模板)成员函数体内部的ADL查找
- 如何在c++中实现内部抽象成员类
- 在类中带有来自另一个类的成员函数的类内部线程
- 另一个结构内部的结构数组的成员变量没有通过引用传递
- 我应该使用 "this" 关键字从成员函数内部访问类成员吗?
- 无法从指针数组或向量内部访问指向对象的成员
- 在模板成员函数内部调用非模板成员函数
- 检索在函数内部使用运算符new分配的类指针对象成员的值时出现的问题