(晃来晃去?)从函数返回的引用不“工作”

时间:2015-06-20 17:38:22

标签: c++ pointers reference unique-ptr

我遵循了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_;
};

这是我的 CComponent &amp; CPosition 类:

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

1 个答案:

答案 0 :(得分:6)

问题在于:

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

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

auto& pos = entity.addComponent<inc::CPosition>();
相关问题