【问题标题】:Prevent const class function from calling non-const class function on reference member防止 const 类函数在引用成员上调用非 const 类函数
【发布时间】:2014-05-12 23:39:25
【问题描述】:

请原谅我的标题相当晦涩,但它确实说明了一切。这就是我的意思

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
}

那么有什么方法可以阻止B::DoSomethingElse() 调用A::DoSomething()
但是,B::DoEventMore() 不是const 应该可以继续调用。

我正在使用 Visual C++ 2013。

上面的代码将演示我的程序中的一个错误。 (在我的场景中,A 类将卸载调用代码的对象/this 指针。)由于 const 正确性的目的是防止此类错误,我只是想知道是否有办法在编译时检查这一点.

在我正在编写的应用程序中,调用该函数似乎一点也不危险。当从 DoEvenMore() 调用它时,结果将是相同的,除了 B 的销毁被推迟到函数运行完成。

【问题讨论】:

    标签: c++ visual-c++ c++11 const-correctness


    【解决方案1】:

    不要使用_a 数据成员直接创建具有const 和非const 重载的访问器函数。这将导致在从Bconst 成员函数中调用时选择const 重载,从而阻止您调用A 的非const 函数。

    A const& GetA() const { return _a; }
    A& GetA() { return _a; }
    
    
    void DoSomethingElse() const
    {
        GetA().DoSomething(); // error
    }
    

    【讨论】:

    • 谢谢,这就是我想要的。没有办法让它隐含,对吧? (省略通话。)
    • @Aidiakapi 如果您的意思是直接访问_a,那么不,没有。由于_a 本身不是const,您可以使用它调用非const 成员函数。
    【解决方案2】:

    “常量”规则使对象本身不可变,但不影响指向/引用对象的常量。如果您想在使用const 方法时访问const 引用,则需要创建一个在constness 上重载的方法,该方法返回引用或const 引用。

    class B {
    private:
        inline A& a() { return _a; }
        inline const A& a() const { return _a; }
    public:
        // ...
    };
    

    【讨论】:

      猜你喜欢
      • 2016-08-17
      • 2015-06-10
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 2020-11-21
      • 2017-10-05
      相关资源
      最近更新 更多