阻止const类函数在引用成员上调用非const类函数

Aid*_*api 5 c++ const-correctness visual-c++ c++11

请原谅我这个相当模糊的标题,但它确实有点说出来.这就是我的意思

class A
{
    void DoSomething(); // non-const
}
Class B
{
public:
    B(A& a) : _a(a) { }
    // const function
    void DoSomethingElse() const
    {
        // Is there a way to disallow this?
        _a.DoSomething();
    }
    void DoEvenMore()
    {
        // Should be OK
        _a.DoSomething();
    }
private:
    // Can't make it const A& because it needs
    // be non-const for non-const functions
    A& _a; // A reference
}
Run Code Online (Sandbox Code Playgroud)

那么有什么方法可以防止B::DoSomethingElse()打电话A::DoSomething()
但是,B::DoEventMore()哪个不const应该继续通话.

我正在使用Visual C++ 2013.

上面的代码将演示我的程序中的错误.(在我的场景中,类A将卸载调用代码的对象/ this指针.)由于const-correctness的目的是防止这些错误,我只是想知道是否有一种方法可以在编译时检查它.

在我正在编写的应用程序中,该函数根本不会发出危险.从DoEvenMore()结果中调用它时将是相同的,除了B在函数运行完成之前推迟销毁.

Pra*_*ian 9

而不是使用_a数据成员直接创建具有const和非const重载的访问器功能.这将导致constconst成员函数内部调用时选择重载B,这反过来又阻止您调用非const函数A.

A const& GetA() const { return _a; }
A& GetA() { return _a; }


void DoSomethingElse() const
{
    GetA().DoSomething(); // error
}
Run Code Online (Sandbox Code Playgroud)


zne*_*eak 5

"constness"的规则使对象本身不可变,但不影响指向/引用对象的常量.如果你想访问一个const参考只有当你使用一个const方法,你需要创建一个重载的常量性返回或者引用或常量引用的方法.

class B {
private:
    inline A& a() { return _a; }
    inline const A& a() const { return _a; }
public:
    // ...
};
Run Code Online (Sandbox Code Playgroud)