-1

I got a function and i want to store some objects into a globally list. Both methods work fine. But do they both create a variable on the heap? What's the difference between them?

vector.push_back(* new object());
vector.push_back(object());

ty for help

DrTosh

DrTosh
  • 1
  • 5
  • Assuming `vector` is an `std::vector`, the first leaks memory (due to dynamically allocating an object that is never released) and the second does not. Both will add a default constructed object, or a copy of one, to the vector (assuming relevant constructors are accessible and implemented appropriately). – Peter May 16 '17 at 14:03

4 Answers4

4

This is wrong:

vector.push_back(* new object());

Don't do that. You're leaking memory, because every new must be matched with a delete and you don't call that. The best thing you can do is never call new at all.

This is OK:

vector.push_back(object());

But in C++11 you can more easily do this:

vector.emplace_back(/*any constructor args go here*/);
John Zwinck
  • 207,363
  • 31
  • 261
  • 371
1

new object() creates an anonymous temporary variable with dynamic storage duration.

* new object() will give you one horrendous memory leak, since you don't store the pointer from new object(), you merely dereference it, and pass it to push_back.

So don't do it that way.

On the other hand, object() is an anonymous temporary with automatic storage duration.

Bathsheba
  • 220,365
  • 33
  • 331
  • 451
1

Both store them in the vector, the vector itself is free in how it wants to store them but it usually uses the free store.

There is a big difference though :

vector.push_back(* new object());

This dynamically allocates an object object and then saves a copy of the object in the vector, the pointer pointing to the newly allocated object is then instantly destroyed.

This way causes a memory leak because you do not delete the object you have allocated with new nor do you save the address for later use.

vector.push_back(object());

This creates a temporary object which is copied and stored in the vector and then destroyed, which is the "correct" way of adding objects to your vector.

Hatted Rooster
  • 33,170
  • 5
  • 52
  • 104
0

They are similar to the following code

object* temp = new object();
vector.push_back(*temp);

object temp;
vector.push_back(object);

It has nothing to do with vector, just no delete is called (and you can't)

Ðаn
  • 10,400
  • 11
  • 57
  • 90
apple apple
  • 5,557
  • 1
  • 12
  • 31