2017-01-30 55 views
0

在我的实验游戏引擎中,我正在用原始指针在堆上创建一些游戏子系统。基本上,我的派生类使用它们的构造函数来调用基础内的受保护的构造函数,以便为它们提供这些子系统的消息。我对这个代码是像这样:如何使用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。

+0

我会小心使用unique_ptr的一切。我建议花一点时间查看需要从整个项目设计的不同翻译单元和类访问何种类型的对象,以及适合此描述的那些对象,而不是使用shared_ptr。现在,对于只存在一次并且应用程序有生命周期的对象,那么拥有该对象的unique_ptr是有意义的。 –

回答

2

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

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

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

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

+1

小心语义上的差异! 'unique_ptr'意味着所有权,原始指针不会。如果你无法为每个新的'unique_ptr'找到相应的'delete',这可能意味着你不拥有这个对象。 – rustyx

+1

@RustyX除非你有代码泄漏每个对象,因为它没有删除,就像问题中的例子。 – Caleth

+0

如果你改变它的签名使用'unique_ptr's(你应该) – Caleth