Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 445
Mr. Boy Avatar asked Aug 09 '26 06:08

Mr. Boy


1 Answers

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).

like image 171
Kevin Avatar answered Aug 10 '26 21:08

Kevin