简体   繁体   English

如何使用 std::reference_wrapper 作为 class 成员?

[英]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) .我使用一个只返回对创建的对象Entity& Create(int id)的引用的库。 In my class, I need to create one of these and store it.在我的 class 中,我需要创建其中一个并存储它。

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.我曾想过使用 class 成员std::reference_wrapper<Entity> MyClass::m_Entity但问题是,我想在调用像MyClass::InitEntity()这样的方法时创建这个 object - 所以我遇到了编译错误“没有可用的默认构造函数”,因为m_Entity未在我的构造函数中初始化。

Is there any way around this, other than to change my class design?除了改变我的 class 设计之外,有什么办法可以解决这个问题吗? 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 ?如果MyClass没有对Entity的有效引用,它是否在有效的 state 中? 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.构造函数初始化指向nullptr的指针, InitEntity function 将其分配给有效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.如果MyClass不在有效的 state 中而没有对Entity的有效引用,那么您可以使用std::reference_wrapper<Entity>并在构造函数中对其进行初始化。

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.当然,您使用哪一个 go 取决于MyClass应该如何使用。 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).就个人而言, std::reference_wrapper的接口对我来说有点尴尬,所以我也会在第二种情况下使用指针(同时仍然确保它始终不为空)。

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

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