How to Instantiate my code utilizing C++11 unique_ptr?

In my experimental game engine I’m currently creating some game sub-systems out on the heap with raw pointers. Basically, my derived classes use their constructors to call a protected constructor within base which news up these sub-systems for them. My code for this is like so:

Entity.h (Base class)

#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 (Derived)

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

How would I update() this code to properly utilize C++11’s unique_ptr? I’m having trouble figuring out how to initialize this smart ptr properly in my classes.

1

Answers


  1. SingerOfTheFall
    0 Votes

    It’s extremely easy. You just change all your raw pointers definitions to std::unique_ptr, and basically you’re done.

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

    Unique pointers are initialized the same way you initialize raw pointers. They will be deleted automatically when the object that holds them dies, so you do not need to release memory manually in the destructor (if you have any delete <...> statements, remove them).

    You also do not need to change the code that uses the pointers, since the objects they point to are accessed with -> operator, same as with raw pointers.

Please signup or login to answer this question.

Signup for an account and start participating in our site today!




Social Signup

You can also login with your Facebook, Twitter or Linkedin account

Log in with Facebook