在我的实验性游戏引擎中,我目前正在使用原始指针在堆上创建一些游戏子系统。基本上,我的派生类使用它们的构造函数在基础内调用受保护的构造函数,从而为它们更新这些子系统。我的代码如下所示:

Entity.h(基类)

#pragma once
#include <memory>

namespace BlazeGraphics{ class Graphics; }
namespace BlazePhysics{ class Physics; }
namespace BlazeInput{ class Controller; }

namespace BlazeGameWorld
{
    class Entity
    {
    protected:
        Entity(BlazeGraphics::Graphics* renderer, BlazePhysics::Physics* physics, BlazeInput::Controller* controller);

        BlazeGraphics::Graphics* renderer;
        BlazePhysics::Physics* physics;
        BlazeInput::Controller* controller;
    };
}


实体.cpp

#include "Graphics/Graphics.h"
#include "Input/Controller.h"
#include "Physics/Physics.h"
#include "Input/Input.h"
#include "Entity.h"

namespace BlazeGameWorld
{
    Entity::Entity()
    {}

    Entity::Entity(BlazeGraphics::Graphics* renderer, BlazePhysics::Physics* physics, BlazeInput::Controller* controller) :
        renderer(renderer),
        physics(physics),
        controller(controller),
        position(0.0f, 0.0f),
        velocity(0.0f, 0.0f)
    {
    }

    Entity::~Entity()
    {
    }
}


Player.cpp(派生)

#include "Graphics/Graphics.h"
#include "Input/Input.h"
#include "Input/PlayerController.h"
#include "Physics/Physics.h"
#include "Player.h"

namespace BlazeGameWorld
{
    Player::Player() :
        Entity(new BlazeGraphics::Graphics, new BlazePhysics::Physics, new BlazeInput::PlayerController)
    {
    }

    Player::~Player()
    {
    }
}


我如何update()此代码以正确利用C ++ 11的unique_ptr?我在弄清楚如何在我的班级中正确初始化此智能ptr时遇到麻烦。

最佳答案

非常简单。您只需将所有原始指针定义更改为std::unique_ptr,基本上就完成了。

std::unique_ptr<BlazeGraphics::Graphics> renderer;


初始化唯一指针的方式与初始化原始指针的方式相同。当包含它们的对象死亡时,它们将被自动删除,因此您不需要在析构函数中手动释放内存(如果有任何delete <...>语句,请将其删除)。

您也不需要更改使用指针的代码,因为它们指向的对象是使用->运算符访问的,与原始指针相同。

09-05 07:11
查看更多