Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

c++ - 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?

question from:https://stackoverflow.com/questions/65849456/how-can-i-use-stdreference-wrapper-as-a-class-member

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...