//Player.h - Header file
#pragma once
#include <iostream>
class Player
{
public:
Player(void);
void SayHi();
~Player(void);
};
#include "Player.h"
Player::Player(void)
{
}
void Player::SayHi()
{
std::cout << "Derp derp" << std::endl;
}
Player::~Player(void)
{
std::cout << "Master Removed me" << std::endl;
}
#include <iostream>
#include "auto_ptr.h"
#include "Player.h"
using namespace std;
int main()
{
Player *dumbpointer = new Player();
dumbpointer->SayHi();
//deallocate memory, and set the pointer to null, thanks Sara
delete dumbpointer;
dumbpointer = NULL;
system("pause");
return 0;
}
//Tell the compiler that we are making a template class, that can support all kind of types.
//The type we later choose, will be stored in the identifer T.
template <class T>
class auto_ptr
{
public:
//explicit = Disable the use of auto_ptr<type> obj = something;
//Constructor
explicit auto_ptr(T* pointer) : ptr(pointer){};
//Deconstructor, will automaticly remove the object from memory when we reach eop (end of program)
~auto_ptr()
{
delete ptr;
}
//Link so that when a pointer is used with our auto_ptr, it will be linked to the contained object inside our auto_ptr instead.
T& operator*()
{
return *ptr;
}
//When we use the operator -> we want it to return the contained object inside auto_ptr too.
T* operator->()
{
return ptr;
}
private:
//Our member attribute, which stores the object we want contained in our auto_ptr
T* ptr;
};
#include <iostream>
#include "auto_ptr.h"
#include "Player.h"
using namespace std;
int main()
{
auto_ptr<Player> smartplayer(new Player);
smartplayer->SayHi();
system("pause");
return 0;
}
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (3)
Commented:
but did i miss the point where you explained why the following statements were in wrong order?
Open in new window
Sara
Author
Commented:Commented:
https://www.experts-exchange.com/articles/1959/C-Smart-pointers.html