vectors with custom class

hello

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 ?
1
2
3
int *p = new int[20];
if(p != 0)
 delete [] p;


and there is the code that I worked on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <vector>
#include <iostream>

class qwe{
private:
	double *x;
	double *y;
	double *z;
public:
	qwe();
	~qwe();
};
qwe::qwe(){
	std::cout<<"cons"<<std::endl;
	x = new double[13];
	y = new double[13];
	z = new double[13];
}
qwe::~qwe(){
	std::cout<<"decons"<<std::endl;
		delete [] x;
		delete [] y;
		delete [] z;
}
void main(){
	std::vector<qwe> test;
	test.push_back(qwe());
	test.push_back(qwe());
	test.push_back(qwe());
}


My english may include mistakes, soryy for them and thanks for your help
U need to overload the copy constructor for class qwe as it contains the pointers to double which are created in constructor.

So the same memory is deleted twice, which is causing the de-allocation.
with this change in the class
 
qwe(const qwe &cSource); 

1
2
3
qwe::qwe(const qwe &cSource){
	
}

its working without any error

thanx for your help
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
qwe::qwe(const qwe &q) {
  int i;

  // allocate variables
  qwe();

  // copy values
  operator = (q);

}

const qwe &qwe::operator = (const qwe &q) {

  // copy x
  for(i = 0; i < 13; i++)
    x[i] = q.x[i];

  // copy y
  for(i = 0; i < 13; i++)
    y[i] = q.y[i];

  // copy z
  for(i = 0; i < 13; i++)
    z[i] = q.z[i];

  return *this;
}
Last edited on
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 = new int[ 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;
}

Topic archived. No new replies allowed.