![](/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.