在我的实验游戏引擎中,我正在用原始指针在堆上创建一些游戏子系统。基本上,我的派生类使用它们的构造函数来调用基础内的受保护的构造函数,以便为它们提供这些子系统的消息。我对这个代码是像这样:如何使用C++ 11 unique_ptr实例化我的代码?
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。
我会小心使用unique_ptr的一切。我建议花一点时间查看需要从整个项目设计的不同翻译单元和类访问何种类型的对象,以及适合此描述的那些对象,而不是使用shared_ptr。现在,对于只存在一次并且应用程序有生命周期的对象,那么拥有该对象的unique_ptr是有意义的。 –