简体   繁体   English

C ++从const对象中返回非const引用

[英]C++ returning non const reference out of const object

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. 当我使用该不可变对象通过点将其自身转换时,我会得到一个const引用。 Since I call getRef of RefContainer object inside the immutable objects compiler says I violate const correctness. 由于我在不可变对象编译器内调用了RefContainer对象的getRef,因此我违反了const正确性。

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: 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

How do I work this out the "right" way (possibly avoiding ugly const casts) ? 我如何以“正确”的方式解决这个问题(可能避免使用丑陋的const cast)?

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. 这样,无论RefContainer实例是否为const对象,都可以将T&引用用作非const。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM