From what I've understood correctly:
scoped_ptr: no overhead, cannot be copied or moved.
unique_ptr: no overhead, cannot be copied, can be moved.
shared_ptr: some overhead (reference counting), can be copied.
Having said that, if there is a need for several owners, then shared_ptr should be used.
Now, in this program below which is a simple implementation of stack in C++. I don't understand which type of smart pointer should be used.
The reason I'm asking this question because both unique_ptr as well as shared_ptr cannot be copied and that is exactly what I'm doing in this implementation of simple stack. I've commented out //HERE in the program where I'm using C++ pointers and if you read the program properly you'll see how the data is getting copied in pretty much all the functions.
GameStateStack.h
#ifndef _H_GAMESTATE_
#define _H_GAMESTATE_
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <memory>
class node
{
public:
std::string gameState;
node * nextGameState; // HERE
};
class GameStateStack
{
private:
node * _topState; // HERE
void Destory();
public:
int gameStatesCount;
void PushGameState(std::string element);
void PopGameState();
std::string CurrentGameState();
GameStateStack();
~GameStateStack();
};
extern GameStateStack state;
#endif
GameStateStack.cpp
#include <iostream>
#include <stdlib.h>
#include <string>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <memory>
#include "GameStateStack.h"
#include "template.h"
GameStateStack state;
GameStateStack::GameStateStack()
{
_topState = NULL;
gameStatesCount = 0;
}
GameStateStack::~GameStateStack()
{
}
void GameStateStack::PushGameState(std::string gameStateName)
{
node *newTopState = new node; // HERE
if (_topState == NULL)
{
newTopState->gameState = gameStateName;
newTopState->nextGameState = NULL;
_topState = newTopState;
gameStatesCount++;
}
else
{
newTopState->gameState = gameStateName;
newTopState->nextGameState = _topState;
_topState = newTopState;
gameStatesCount++;
}
}
void GameStateStack::PopGameState()
{
if (_topState == NULL)
std::cout << "Error: no gamestates available to pop";
else
{
node * old = _topState; // HERE
_topState = _topState->nextGameState;
delete(old);
gameStatesCount--;
}
}
std::string GameStateStack::CurrentGameState()
{
node *temp; // HERE
temp = _topState;
return temp->gameState;
}
void GameStateStack::Destory()
{
node *abc; // HERE
delete _topState;
delete abc->nextGameState;
}