[英]C++ Difference Between Const Reference to Non Const Object and Non Const Reference to Non Const Object
[英]C++ returning non const reference out of const object
我有包含參考的結構
template <class T>
struct RefContainer {
RefContainer(T& t) : _r(t) {}
T& getRef() {
return _r;
}
private:
T& _r;
};
現在,另一個不可變的對象在其內部使用此結構,並在其中包含此對象,如下所示:
RefContainer<char> _c;
當我使用該不可變對象通過點將其自身轉換時,我會得到一個const引用。 由於我在不可變對象編譯器內調用了RefContainer對象的getRef,因此我違反了const正確性。
RefContainer本身必須持有非常量左值引用,但我很想將對不可變對象的調用鏈接起來,以創建新對象,如下所示:
ImmubableObject obj;
auto newObj = obj.copyWithSomeAttributes().modifyWithThisString("str");
// I'm on C++11 btw, so I can use everything C++11 has to offer
我如何以“正確”的方式解決這個問題(可能避免使用丑陋的const cast)?
您應該嘗試這樣的事情:
template <class T>
struct RefContainer {
RefContainer(T& t) : _r(t) {}
T& getRef() const {
// ^^^^^
return _r;
}
private:
T& _r;
};
這樣,無論RefContainer
實例是否為const
對象,都可以將T&
引用用作非const。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.