关于“Effective C ++”方法的编译器警告以避免const和非const成员函数中的重复 [英] Compiler warning on "Effective C++"s method to avoid duplication in const and non-const member functions

查看:181
本文介绍了关于“Effective C ++”方法的编译器警告以避免const和非const成员函数中的重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题已更新。请检查代码。

以下代码是使用VC ++ 2012年11月CTP编译的。 Scott Meyers的书 Effective C ++ 建议我们应该使用避免在const和非const成员函数中重复的方法。但是,以下代码会产生警告(级别1)。因为WDK构建工具将警告视为错误,因此以下代码无法成功编译。

The following code was compiled with VC++ Nov 2012 CTP. Scott Meyers' book "Effective C++" recommend that we should use the method of to avoid duplication in const and non-const member functions. However, the following code cause a warning (level 1). Because WDK build tool treats warnings as errors, so the following code cannot be compiled successfully.

是否还有其他更好的方法?

Is there other better method?

struct A
{
    int n;

    A(int n)
        : n(n)
    {}

    int Get() const
    {
        return n;
    }

    int Get()
    {
        return static_cast<const decltype(*this)&>(*this).Get();
    }
};

int main()
{
    const A a(8);

    //
    // warning C4717: 'A::Get' : recursive on all control paths,
    // function will cause runtime stack overflow
    //
    a.Get(); 
}


推荐答案

的两个 Get 方法,因此编译器是正确的; const Get 方法正在调用自身。现在你不高兴你的构建工具将警告视为错误吗? :)

You've transposed the bodies of the two Get methods, so the compiler is correct; the const Get method is calling itself. Aren't you glad now that your build tool treats warnings as errors? :)

将它们轮换:

int& Get()
{
    return const_cast<int&>(static_cast<const A&>(*this).Get());
}

const int& Get() const
{
    return n;
}

这篇关于关于“Effective C ++”方法的编译器警告以避免const和非const成员函数中的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆