destructor executes while name still in scope?

Why does this code cause a crash? As it happens, the call to equal finds 'items' already deleted (what am I missing?). Thanks for any help.

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
  class X {

public:

	X(int kk) : k(kk) {
		items = new int[k];
		for (int i = 0; i < k; i++)
			items[i] = i;
	}

	~X() {
		delete[] items;
	}

	void equal(X d) {}

private:
	int k;
	int *items;
};

int main()
{
	X e(2);
	X f(2);

	e.equal(f);

	return 0;
}
Are you sure that's what's happening?

As you haven't provided a copy constuctor (so one that does a shallow copy is being generated for you) and are passing your object to equal() by value, the destructor will end up trying to "double delete" items.

Andy
Last edited on
thanks much
Topic archived. No new replies allowed.