I am trying to create a vector that holds qwe class, In qwe class, constructor allocate places for x, y and z variables. In deconstructor these allocated memories are deleted. However when I push a new instance of qwe in my vector.
1-It calls deconstructor many times and that couse delete x,y,z variables more than once, by the way I dont know why deconstructor is called ?
2- what should I do to learn if a pointer is deleted before
is this correct ?
Vectors frequently do funny things, like copying objects and deleting the originals.
When you have a class that allocates memory for itself, it's always a good idea to overload the = operator as well as creating a constructor that copies another object of the same class.
I recommend adding the following constructor and function:
One other thing in regards to the original post....
new will throw a bad_alloc exception if there isn't sufficient memory to allocate; therefore, unless you are using the nothrow version of new (which you're not by default), the correct way to check for new failure is as follows:
1 2 3 4 5 6 7 8
try {
int* p = newint[ 50 ];
// rest of code here...
} catch( std::bad_alloc const& ) {
// Good luck recovering from an out of memory error.... for example,
// even doing this is likely to not work at this point:
cerr << "Out of memory" << endl;
}