gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:37:00 30 4
gpt4 key购买 nike

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

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

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

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

跟随我的 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>();

关于c++ - (悬空?)从函数返回的引用不是 "work",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30957027/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com