0

With following source files:

Obj.h

class Obj
{
public:
    Obj();
    Obj(const Obj &other);
    ~Obj();
};

Obj.cpp

#include <iostream>
#include "Obj.h"

using namespace std;

Obj::Obj(){ cout << "create "; }

Obj::Obj(const Obj &other){ cout << "copy "; }

Obj::~Obj(){ cout << "delete "; }

main.cpp

#include <vector>
#include "Obj.h"

using namespace std;

vector<Obj> objects;

int main(int argc, char** argv)
{
    for (int i = 0; i < 4; i++)
        objects.push_back(*(new Obj));
    //system("pause");
}

The program outputs: create copy create copy copy delete create copy copy copy delete delete create copy copy copy copy delete delete delete

Why can't it be just 'create, create, create, create'?

I'm out of ideas how to fix that problem and it doesn't help that I've just started learning pointers and the c++ itself. Any help appreciated!

I'm using Visual Studio 2017 with whatever compiler there's by default.

Werek
  • 123
  • 7
  • 2
    Explain this `*(new Obj)` to your [rubber duck](https://en.wikipedia.org/wiki/Rubber_duck_debugging). – juanchopanza Oct 10 '18 at 21:17
  • @NeilButterworth I've changed the dupe target as the OP has the needed constructors. What they are seeing is the vector growing and copying internally. – NathanOliver Oct 10 '18 at 21:20
  • OP: Do note that `objects.push_back(*(new Obj));` is really never what you want to do. This is going to cause you a memory leak because you don't `delete` all the objects when you are done. You can just use `objects.push_back(Obj{});` instead. – NathanOliver Oct 10 '18 at 21:22

0 Answers0