Search code examples
c++vectormemory-managementheap-memorypush-back

c++ vector - what's the difference between push_back(*new obj()) and push_back(obj())?


I am currently having an issue related to:

vector<myObj> myVector;

Q1. Please tell me the difference between the following two lines:

a) myVector.push_back(*new myObj());
b) myVector.push_back(myObj());

NOTE: I realise that line a) is bad practice as it is causing a memory leak by allocating the myObj's contents dynamically before copying it into the vector and therefore can't be freed...

However, I was under the assumption that both of these lines should result in the vector containing the exact same contents, though it appears that this assumption is incorrect. The software I am currently developing RUNS fine using line a) (I know, I know this is causing a leak, please try to disregard this just for now) but crashes with various different exc_bad_access errors on line b).

Q2. can anyone explain why this might be?

EDIT: When posting this I originally assumed that my issue must be related to some difference in the resulting vector contents, however my problem was actually related to fulfilling the "Rule of Three" http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming) Thank you to @WhozCraig , @juanchopanza & @Alex Antonov for your help!


Solution

  • In line a) you're creating 2 objects and you have the following method calls:
    1) Default constructor for first object
    2) Copy constructor for second object

    In line b) you're creating 2 objects as well but you have the following method calls:
    1) Default constructor for first object
    2) Copy constructor for second object
    3) Destructor for first object

    So obviously the line a) works because the destructor is not called. It implies that most probably in line b) you're deallocating/freeing some resource (e.g. a dynamically allocated memory) in destructor and then trying to access that resource by the second object. In that case you need to implement the copy constructor properly. E.g. you need to allocate new memory/object in copy constructor instead of simply copying a pointer to memory/object.