相关疑难解决方法(0)

C++:为什么const_cast是邪恶的?

我一直听到这句话,但我无法真正找到const_cast是邪恶的原因.

在以下示例中:

template <typename T>
void OscillatorToFieldTransformer<T>::setOscillator(const SysOscillatorBase<T> &src)
{
    oscillatorSrc = const_cast<SysOscillatorBase<T>*>(&src);
}
Run Code Online (Sandbox Code Playgroud)

我正在使用引用,并使用const,我保护我的引用不被更改.另一方面,如果我不使用const_cast,代码将无法编译.为什么const_cast在这里不好?

这同样适用于以下示例:

template <typename T>
void SysSystemBase<T>::addOscillator(const SysOscillatorBase<T> &src)
{
    bool alreadyThere = 0;
    for(unsigned long i = 0; i < oscillators.size(); i++)
    {
        if(&src == oscillators[i])
        {
            alreadyThere = 1;
            break;
        }
    }
    if(!alreadyThere)
    {
        oscillators.push_back(const_cast<SysOscillatorBase<T>*>(&src));
    }
}
Run Code Online (Sandbox Code Playgroud)

请给我一些例子,我可以看到使用const_cast是一个坏主意/不专业.

谢谢你的任何努力:)

c++ pointers casting const const-cast

14
推荐指数
3
解决办法
9538
查看次数

const_cast的未定义行为

我希望有人能够准确地澄清C++中未定义行为的含义.给定以下类定义:

class Foo
{
public:
    explicit Foo(int Value): m_Int(Value) { }
    void SetValue(int Value) { m_Int = Value; }

private:
    Foo(const Foo& rhs);
    const Foo& operator=(const Foo& rhs);

private:
    int m_Int;
};
Run Code Online (Sandbox Code Playgroud)

如果我已经正确理解了以下代码中的引用和指针的两个const_casts将删除Foo类型的原始对象的常量,但是通过指针或引用修改此对象的任何尝试都将导致未定义的行为.

int main()
{
    const Foo MyConstFoo(0);
    Foo& rFoo = const_cast<Foo&>(MyConstFoo);
    Foo* pFoo = const_cast<Foo*>(&MyConstFoo);

    //MyConstFoo.SetValue(1);   //Error as MyConstFoo is const
    rFoo.SetValue(2);           //Undefined behaviour
    pFoo->SetValue(3);          //Undefined behaviour

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

让我感到困惑的是为什么这似乎有效并将修改原始的const对象,但是甚至没有提示我发出警告通知我这种行为是未定义的.从广义上讲,我知道const_casts是不受欢迎的,但是我可以想象一种情况是缺乏对C风格的强制转换可以导致const_cast的意识,而不会被注意到,例如:

Foo& rAnotherFoo = (Foo&)MyConstFoo;
Foo* pAnotherFoo = (Foo*)&MyConstFoo;

rAnotherFoo->SetValue(4);
pAnotherFoo->SetValue(5);
Run Code Online (Sandbox Code Playgroud)

在什么情况下这种行为会导致致命的运行时错误?是否有一些编译器设置可以设置为警告我这种(可能)危险的行为?

注意:我使用的是MSVC2008.

c++ const-cast undefined-behavior

9
推荐指数
2
解决办法
2793
查看次数

标签 统计

c++ ×2

const-cast ×2

casting ×1

const ×1

pointers ×1

undefined-behavior ×1