0

I have a question and I can't find an answer anywhere. However, there is some code I have to show:

  #include "Vector2D"

    class something
    {
        Vector2D * p_Position;
      public:
        something(){p_Position = new Vector2D;}
        ~something(){delete p_Position;}
    };

    int main()
{
    std::list<something> Somethinglist;

    Somethinglist.push_back(something());

    Somethinglist.clear();
    return 0;
}

So, this will lead to an assertion fail when it comes to the .clear() function. So I tried out a few things. First of all this code completely works if I just don't put the delete p_Position in the deconstructor. Why is that? Does the STL list .clear() function automatically destroy dynamic Pointers? Or a rather direct question: How can I fix this code?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tilman Zuckmantel
  • 643
  • 1
  • 6
  • 18

2 Answers2

5

std::list::push_back() takes its argument by value (i.e. a copy is produced), and that's a real problem because you haven't followed the Rule of Three.

Community
  • 1
  • 1
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • I'm always wondering why isn't the language designed so that std containers can hold **references** to the objects added to them. (I understand that as it's currently standing, it's impossible, since dynamic memory management is required **and** we can't have pointers to references, but stil...) –  Jul 06 '13 at 05:03
  • so basicly, what i am trying to do is not possible? – Tilman Zuckmantel Jul 06 '13 at 05:22
  • 1
    @TilmanZuckmantel: Did you read the question/answer I linked to? – Oliver Charlesworth Jul 06 '13 at 05:23
1

First of all this code completly works if i just don't put the delete p_Position in the deconstructor.

Because p_Position won't be deallocated if you didn't put it in destructor. it causes memory leak.

Why is that. Does the STL list .clear() function automaticly destroy dynamic Pointers?

STL container keeps a copy of original object. when .clear(), these objects will be freed and their destructors will be called.

Or a rather direct question: How can i fix this code?

Follow Rule of Three.

OR use smart pointer

#include <memory>
class something
{
    std::unique_ptr<Vector2D> p_Position;
  public:
    something(){}
    ~something(){}
};

OR use it without pointer

class something
{
   Vector2D p_Position;
  public:
    something(){}
};
Community
  • 1
  • 1
billz
  • 44,644
  • 9
  • 83
  • 100