相关疑难解决方法(0)

C++成员函数中的"if(!this)"有多糟糕?

如果我遇到if (!this) return;应用程序中的旧代码,那么风险有多严重?这是一个危险的滴答作响的定时炸弹需要立即在应用程序范围内搜索并摧毁努力,还是更像是可以安静地留在原点的代码气味?

当然,我不打算编写执行此操作的代码.相反,我最近在我们的应用程序的许多部分使用的旧核心库中发现了一些东西.

想象一下,一个CLookupThingy类具有非虚拟 CThingy *CLookupThingy::Lookup( name )成员函数.显然,那些牛仔时代的程序员遇到了许多崩溃事件,其中NULL CLookupThingy *是从函数传递的,而不是修复数百个调用站点,他悄悄地修复了Lookup():

CThingy *CLookupThingy::Lookup( name ) 
{
   if (!this)
   {
      return NULL;
   }
   // else do the lookup code...
}

// now the above can be used like
CLookupThingy *GetLookup() 
{
  if (notReady()) return NULL;
  // else etc...
}

CThingy *pFoo = GetLookup()->Lookup( "foo" ); // will set pFoo to NULL without crashing
Run Code Online (Sandbox Code Playgroud)

我本周早些时候发现了这颗宝石,但现在我是否应该解决这个问题.这是我们所有应用程序使用的核心库.其中一些应用程序已经发送给数百万客户,它似乎工作正常; 该代码没有崩溃或其他错误.删除if !this查找函数将意味着修复数千个可能传递NULL的调用站点; 不可避免地会有一些人被遗漏,引入新的错误,这些错误将在未来一年的发展中随机出现.

所以除非绝对必要,否则我倾向于不管它. …

c++ gcc visual-c++

73
推荐指数
7
解决办法
4969
查看次数

什么时候应该在C++中使用"this"关键字?

可能重复:
在C++中过度使用此代码气味

多年前,我养成了在访问成员变量时使用this->的习惯.我知道这不是绝对必要的,但我认为它更清楚.

然后,在某些时候,我开始更喜欢更简约的风格,并停止了这种做法......

最近我被一个更年轻的同龄人问到我是否认为这是一个好主意而且我发现我对自己的偏好没有真正的答案...这真的是一个完全风格的选择还是有真正的原因为什么不在成员变量访问前加上this->更好?

c++ coding-style

41
推荐指数
5
解决办法
6万
查看次数

在C++模板中进行名称查找

我有一些不使用-fpermissive选项而不再编译的C++代码.这是我不能分享的专有代码,但我认为我已经能够提取一个简单的测试用例来证明这个问题.这是g ++的输出

template_eg.cpp: In instantiation of 'void Special_List<T>::do_other_stuff(T*) [with T = int]':
template_eg.cpp:27:35:   required from here
template_eg.cpp:18:25: error: 'next' was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]
template_eg.cpp:18:25: note: declarations in dependent base 'List<int>' are not found by unqualified lookup
template_eg.cpp:18:25: note: use 'this->next' instead
Run Code Online (Sandbox Code Playgroud)

所以这是产生问题的代码:

template<class T> class List  
{
        public: 
        void next(T*){
            cout<<"Doing some stuff"<<endl;
        }       
};

template<class T> class Special_List: public List<T>
{
    public:
        void …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance templates

39
推荐指数
3
解决办法
7584
查看次数

有没有理由使用这个 - >

我用C++编程多年,但我对一件事情仍有疑问.在其他人代码的许多地方,我看到类似的东西:

void Classx::memberfunction()
{
    this->doSomething();
}
Run Code Online (Sandbox Code Playgroud)

如果我需要导入/使用该代码,我只需删除this-> part,我从未见过任何破坏或有一些副作用.

void Classx::memberfunction()
{
    doSomething();
}
Run Code Online (Sandbox Code Playgroud)

那么,你知道使用这种结构的任何理由吗?

编辑:请注意我在这里谈论成员函数,而不是变量.我知道当你想要区分成员变量和函数参数时,可以使用它.

编辑:明显重复: 有没有理由不使用"这个"("自我","我",......)?

c++

16
推荐指数
4
解决办法
5786
查看次数

什么时候应该使用?

我想知道是否应该使用这两个:

void SomeClass::someFunc(int powder)
{
     this->powder = powder;
}

//and
void SomeClass::someFunc(bool enabled)
{
     this->isEnabled = enabled;
}
Run Code Online (Sandbox Code Playgroud)

我想知道后者是否必须正确或如果isEnabled =启用就足够了.

谢谢

c++

5
推荐指数
1
解决办法
390
查看次数

标签 统计

c++ ×5

coding-style ×1

gcc ×1

inheritance ×1

templates ×1

visual-c++ ×1