STL dynamic pointer help

So I am just trying to dynamically create a list of ships. All goes according to plan until my pointer tries to create the 6th element of the list. My progam crashes once trying to retrieve the string value of the 6th element. I don't know what is causing the problem and I'm not sure how to fix this issue.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
  int main()
{
    list<Ship*>myFleet;
    list<Ship*>::iterator sItr;

    Ship * p;
    SubmergedShip * n;



    ///Initialize the entire fleet
    p = new Ship("Aircraft Carrier", 'a', 10000, 10000, 50, false);
    myFleet.push_back(p);

    p = new Ship("Missle Cruiser", 'b', 6000, 8000, 30, false);
    p->calculateBearing(10000, 10000);
    myFleet.push_back(p);

    p = new Ship("DDG", 'c', 14000, 8000, 30, true);
    p->calculateBearing(10000, 10000);
    myFleet.push_back(p);


    p = new Ship("Frigate", 'd', 4000, 4000, 30, false);
    p->calculateBearing(10000, 10000);
    myFleet.push_back(p);


    p = new Ship("DDG", 'e', 16000, 4000, 30, false);
    p->calculateBearing(10000, 10000);
    myFleet.push_back(p);


    p = new Ship("Resupply", 'f', 4000, 0, 43, false);
    p->calculateBearing(10000, 10000);
    myFleet.push_back(p);


    n = new SubmergedShip("Submarine", 'g', 10000, 5000, -350, 35, false);
    n->calculateBearing(10000,10000);
    myFleet.push_back(n);

    delete p;
    delete n;

 
    for(sItr = myFleet.begin(); sItr != myFleet.end(); sItr++){
        cout<<(*sItr)->getDesignation()<<endl;
    }
> I'm not sure how to fix this issue.

Automate resource management with std::unique_ptr<>, perhaps?
http://en.cppreference.com/w/cpp/memory/unique_ptr

Something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
    ///Initialize the entire fleet
    std::list< std::unique_ptr<Ship> > myFleet ;
    
    myFleet.push_back( std::make_unique<Ship>("Aircraft Carrier", 'a', 10000, 10000, 50, false) );
    myFleet.push_back( std::make_unique<Ship>("Missle Cruiser", 'b', 6000, 8000, 30, false) );
    myFleet.push_back( std::make_unique<Ship>("DDG", 'c', 14000, 8000, 30, true) );
    myFleet.push_back( std::make_unique<Ship>("Frigate", 'd', 4000, 4000, 30, false) );
    myFleet.push_back( std::make_unique<Ship>("Resupply", 'f', 4000, 0, 43, false) );
    myFleet.push_back( std::make_unique<SubmergedShip>("Submarine", 'g', 10000, 5000, -350, 35, false) ) ;

    for( auto& ptr : myFleet ) ptr->calculateBearing(10000, 10000);

    for( auto& ptr : myFleet ) std::cout << ptr->getDesignation() << '\n' ;
    
    // etc.
}
Topic archived. No new replies allowed.