【发布时间】: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