简体   繁体   中英

How can I use std::reference_wrapper as a class member?

I use a library that only returns references to created objects Entity& Create(int id) . In my class, I need to create one of these and store it.

I had thought to use class member std::reference_wrapper<Entity> MyClass::m_Entity but the problem is, I would like to create this object in a call to a method like MyClass::InitEntity() – so I run into a compile error "no default constructor available" because m_Entity is not initialised in my constructor.

Is there any way around this, other than to change my class design? Or is this a case where using pointers would make more sense?

Is MyClass in a valid state if it doesn't have a valid reference to an Entity ? If it is, then you should use a pointer. The constructor initializes the pointer to nullptr , and the InitEntity function assigns it to the address of a valid Entity object.

class MyClass
{
public:
    MyClass(): _entity(nullptr) {}
    void InitEntity() { _entity = &Create(123); }
    void doSomethingWithEntity()
    {
        if (_entity) ...
    }

private:
    Entity *_entity;
};

If MyClass isn't in a valid state without a valid reference to an Entity , then you can use a std::reference_wrapper<Entity> and initialize it in the constructor.

class MyClass
{
public:
    MyClass(): _entity(Create(123)) {}
    void doSomethingWithEntity()
    {
        ...
    }

private:
    std::reference_wrapper<Entity> _entity;
};

Of course which one you go with depends on how MyClass is supposed to be used. Personally, the interface for std::reference_wrapper is a little awkward for me, so I'd use a pointer in the second case as well (while still ensuring that it's always not null).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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