(晃来晃去?从函数返回的引用不会"work"

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

本文关键字:引用 work 返回 晃来晃去 函数      更新时间:2023-10-16

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

然后,我尝试重写类CEntity,CComponent和测试CPosition(主要来自Romeo的视频/代码的记忆)。 我遇到的问题是,在我的主要情况下,我在堆栈上创建了一个 CEntity 并添加一个组件。当我通过addComponent()添加组件时,我获取了对新创建的组件的引用,该组件由addComponent()返回。

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

谁能指出我在这里做错了什么?

我的CEntity课程:

#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_;
};

这是我的CComponentCPosition课程:

// 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};
};

的主要功能:

#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()返回一个引用,并且该函数中的所有内容都很好(据我所知,没有悬而未决的引用问题)。但是auto不会推断出引用类型,除非你告诉它 - 所以你只是在那里制作一个副本。解决方案只是告诉它推断出一个参考:

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