C ++从const对象返回非const引用(C++ returning non const reference out of const object)

编程入门 行业动态 更新时间:2024-10-10 07:23:21
C ++从const对象返回非const引用(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本身必须保持非const左值引用,但我喜欢链接不可变对象的调用以创建新的类似:

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演员)?

I have structure that contains reference in it

template <class T> struct RefContainer { RefContainer(T& t) : _r(t) {} T& getRef() { return _r; } private: T& _r; };

Now, another object, which is immutable uses this structure inside itself and has this object in it like so:

RefContainer<char> _c;

When I use that immutable object to transform itself with a dot I get a const reference. Since I call getRef of RefContainer object inside the immutable objects compiler says I violate const correctness.

The RefContainer itself has to hold non-const lvalue reference but I'd love to chain calls on immutable object to create new ones like so:

ImmubableObject obj; auto newObj = obj.copyWithSomeAttributes().modifyWithThisString("str"); // I'm on C++11 btw, so I can use everything C++11 has to offer

How do I work this out the "right" way (possibly avoiding ugly const casts) ?

最满意答案

你应该尝试这样的事情:

template <class T> struct RefContainer { RefContainer(T& t) : _r(t) {} T& getRef() const { // ^^^^^ return _r; } private: T& _r; };

这样,无论RefContainer实例是否为const对象, T& reference都可以用作非const。

You should try something like this:

template <class T> struct RefContainer { RefContainer(T& t) : _r(t) {} T& getRef() const { // ^^^^^ return _r; } private: T& _r; };

This way, the T& reference can be used as non const, regardless the RefContainer instance is a const object or not.

更多推荐

本文发布于:2023-04-29 09:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335615.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   const   returning   object   reference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!