![](/img/trans.png)
[英]How to avoid code duplication implementing const and non-const iterators?
[英]How to avoid repeated const and non-const virtual functions ? is it possible?
假设我有一个具有以下虚函数的基类:
virtual int* get(){ return nullptr; }
和
我想提供一个const
版本(请记住,我在遗留代码中有50个不同的实现)
const int* get() const { return const_cast<decltype(this)>(this)->GetReturn(); };//NEED CODE BADLY: const_cast :/
但是这个想法需要使用const_cast
- scott meyer在他的书中建议这种方法(尽管情况正好相反) - 但它是否真的安全(如果是的话,它是否也是'面向未来的'?)来自例如成员const?
我可以通过一些搜索/替换来改变这种情况,但是所有类的实现似乎都是“复制粘贴”反模式。
但它真的很安全吗
不幸的是:
变式1:
class C
{
int n;
public:
int* get() { ++n; return &n; }
int const* get() const { return const_cast<decltype(this)>(this)->get(); }
};
变式2:
class C
{
int const n;
public:
int const* get() const { return &n; }
int* get() { return const_cast<int*>(const_cast<decltype(this) const*>(this)->get()); }
void demo() // non-const!
{
++*get();
}
};
承认,第二种情况可能不太可能 - 但也不是不可能。 因此,在这两个变体中的任何一个中,隐藏的机会都会引发未定义的行为......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.