Vector of pointers , am i using delete correctly here ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <vector>

class player{
private:
    int id;
public:
    void setid(int i){id=i;}
    int getid(void){return id;}
};

int main(){

    std::vector<player*> playerlist;
    playerlist.push_back(new (std::nothrow) player);

    playerlist[0]->setid(0);
    printf("%d",playerlist[0]->getid());

    delete playerlist[0];
    return 0;
}


I would also like to ask one more question:

Why line 14 must be like it is and not like this :
std::vector<player> * playerlist;

i'm use to declaring pointers like this:
int *a, *b, *c;

Thank you for your help.
youre using delete correctly. Because inside the <> you must put in the type, and since its a pointer to player, you must put player*
Is there a way to check if it was deleted ?
You can make a destructor and put your delete in there, and print out when it gets executed.
Last edited on
ok but if i put this line after my delete :
printf("%d",playerlist[0]->getid());

even though i have deleted i was still allowed to use getid why?
Is there a way to check if it was deleted ?
When you call delete, object is either succesfully deleted or your program crashes.

Why line 14 must be like it is and not like this :
std::vector<player> * playerlist; is a pointer to the vector of players.
std::vector<player*> playerlist; is a vector of player pointers.

Generally you should not operate on raw pointers. Use inique_ptr, whch automatically does cleanup:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <vector>
#include <iostream>
#include <memory>

class player{
private:
    int id;
public:
    void setid(int i){id=i;}
    int getid(void){return id;}
};

int main(){

    std::vector<std::unique_ptr<player>> playerlist;
    playerlist.emplace_back(new player); 
    //Or playerlist.emplace_back(std::make_unique<player>());
    //for additional safety (C++14).

    playerlist[0]->setid(0);
    std::cout << playerlist[0]->getid();
    //No delete is needed, unique ponter handles that
}

even though i have deleted i was still allowed to use getid why?
You just got lucky that undefined behavior didn't lead to something worse
http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope
Last edited on
Thank you armonsafai & MiiNiPaa for your answers , also the link you gave me
MiiNiPaa is pure gold i must save it and burn it to my brain.


You just got lucky that undefined behavior didn't lead to something worse
http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope
Topic archived. No new replies allowed.