【发布时间】:2017-06-15 07:41:07
【问题描述】:
在我的实验游戏引擎中,我目前正在使用原始指针在堆上创建一些游戏子系统。基本上,我的派生类使用它们的构造函数来调用 base 中的受保护构造函数,该构造函数会为它们更新这些子系统。我的代码是这样的:
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 是有意义的。
标签: c++ c++11 inheritance smart-pointers