(悬空?)从函数返回的引用不 "work"

(Dangling?) Reference returned from function does not "work"

我遵循了 V. Romeo 关于实体管理的教程(在 GitHub & Youtube 上)。

然后我尝试重写 classes CEntityCComponent 并测试 CPosition(主要来自罗密欧video/code的记忆)。 我遇到的问题是,在我的 main 中,我在堆栈上创建了一个 CEntity 并添加了一个组件。当我通过 addComponent() 添加组件时,我获取了对新创建组件的引用,由 addComponent().

返回

当我现在想通过返回的引用修改组件时,我所做的更改不会反映回实体(的组件)。看起来像是对我的悬而未决的引用,但我无法找到我犯的错误。

任何人都可以指出我在这里做错了什么吗?

关注我的 CEntity class:

#include <array>
#include <bitset>
#include <memory>
#include <cassert>
#include <stdexcept>

namespace inc
{

using ComponentID = unsigned int;

ComponentID getNewID()
{
    static ComponentID id = 0;
    return id++;
}

template <typename T>
ComponentID getComponentID()
{
    static ComponentID component_id = getNewID();
    return component_id;
}

// Forward declarations used by CEntity:
struct CComponent;

class CEntity
{
public:
    static const ComponentID MAX_COMPONENTS = 30;
    using ComponentArray                    = std::array<std::unique_ptr<CComponent>, CEntity::MAX_COMPONENTS>;
    using ComponentBitset                   = std::bitset<MAX_COMPONENTS>;

public:
    CEntity()
    {
    }

    ~CEntity()
    {
    }

    template <typename T, typename... TArgs>
    T& addComponent(TArgs&&... Args)
    {
        // Ensure that CComponent is base of T:
        static_assert(std::is_base_of<CComponent, T>::value, "CEntity::addComponent(): Component has to be derived from CComponent.");

        // Get id for component type
        auto component_id = getComponentID<T>();
        assert(component_id <= MAX_COMPONENTS);

        // Create component
        auto component     = std::make_unique<T>(std::forward<TArgs>(Args)...);
        auto component_ptr = component.get();

        // Initialize the component
        component->entity = this;
        component->init();

        // Store component
        components_[component_id] = std::move(component);

        // Set component flag
        component_bitset_[component_id] = true;

        return *component_ptr;
    }

private:
    ComponentArray components_;
    ComponentBitset component_bitset_;
};

这里是我的 CComponent & CPosition classes:

// Forward required by CComponent
class CEntity;

// Abstract base class for components
struct CComponent
{
    using TimeSlice = float;

    // Pointer to parent entity
    CEntity* entity;

    virtual ~CComponent() {}

    virtual void init() {}
    virtual void update(const TimeSlice DT) {}
    virtual void draw() const {}
};

struct CPosition : public CComponent
{
    sf::Vector2f position{0,0};
};

我的 main 函数:

#include "Entity.h"
#include "ComponentCollection.h"
int main()
{
    inc::CEntity entity;

    auto pos = entity.addComponent<inc::CPosition>();
    pos.position.x = 1;
    return 0;
}

问题在这里:

auto pos = entity.addComponent<inc::CPosition>();
^^^^^

addComponent() returns 一个参考,并且该函数中的所有内容都很好(据我所知没有悬空参考问题)。但是 auto 不会推断出引用类型,除非您告诉它 - 所以您只是在那里制作一个副本。解决方案就是告诉它推导一个参考:

auto& pos = entity.addComponent<inc::CPosition>();