如何利用C ++ 11 unique_ptr实例化我的代码?

时间:2017-01-30 07:43:07

标签: c++ c++11 inheritance smart-pointers

在我的实验游戏引擎中,我目前正在使用原始指针在堆上创建一些游戏子系统。基本上,我的派生类使用它们的构造函数来调用基础内的受保护构造函数,这些构造函数为这些子系统提供新闻。我的代码是这样的:

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

Entity.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()
    {
    }
}

如何更新()此代码以正确使用C ++ 11的unique_ptr?我在找到如何在课堂上正确初始化这个智能ptr时遇到了麻烦。

1 个答案:

答案 0 :(得分:2)

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

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

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

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