Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...