在C ++中过度使用`this` [英] Excessive use of `this` in C++
问题描述
我正在处理一个大型代码库,其中使用以下构造
I'm dealing with a large code base that uses the following construct throughout
class MyClass
{
public:
void f(int x);
private:
int x;
};
void MyClass::f(int x)
{
'
'
this->x = x;
'
'
}
因此更喜欢使用形式
class MyClass
{
public:
void f(int x);
private:
int _x;
};
void MyClass::f(int x)
{
'
'
_x = x;
'
'
}
是更简洁(更少的代码=更少的潜在错误),我不喜欢在同一时间范围内,我可以避免同一名称的多个变量。也就是说,我看到以前的用法越来越频繁,这些天。有没有任何上升的第二种方法,我不知道? (例如对编译时间的影响,使用模板化代码等等)。这两种方法的优点是否足够重视另一方的重构?原因我问,虽然我不喜欢在代码中的第二种方法,努力量和引入更多的bug的相关风险不是非常值得重构。
The reasons I prefer the latter are that it is more succinct (less code = fewer potential bugs), and that I don't like having multiple variables of the same name in scope at the same time where I can avoid it. That said, I am seeing the former usage more and more often these days. Is there any upside to second approach that I am unaware of? (e.g. effect on compile time, use with templated code, etc...) Are the advantages of either approach significant enough merit a refactor to the other? Reason I ask, that while I don't like the second approach present in the code, the amount of effort and associated risk of introducing further bugs don't quite merit a refactor.
推荐答案
你的版本有点干净,但是当你使用它,我会:
Your version is a bit cleaner, but while you're at it, I would:
- 避免引导下划线:_x是确定的,直到有人选择_MyField作为保留名称。不允许使用大写字母后的初始下划线作为变量名。请参阅:在C ++标识符中使用下划线有什么规定?
- 将属性设为私有或受保护:如果编译时更改是安全的,您将确保您的设置器将被使用。
- 这个 - >故事有一个用途,例如在模板代码,使字段名取决于您的类型(可以解决一些查找问题)。
通过使用显式this->(用g ++ 3.4.3测试):
A small example of name resolutions which are fixed by using an explicit this-> (tested with g++ 3.4.3):
#include <iostream>
#include <ostream>
class A
{
public:
int g_;
A() : g_(1) {}
const char* f() { return __FUNCTION__; }
};
const char* f() { return __FUNCTION__; }
int g_ = -1;
template < typename Base >
struct Derived : public Base
{
void print_conflicts()
{
std::cout << f() << std::endl; // Calls ::f()
std::cout << this->f() << std::endl; // Calls A::f()
std::cout << g_ << std::endl; // Prints global g_
std::cout << this->g_ << std::endl; // Prints A::g_
}
};
int main(int argc, char* argv[])
{
Derived< A >().print_conflicts();
return EXIT_SUCCESS;
}
这篇关于在C ++中过度使用`this`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!