• 12
• 12
• 9
• 10
• 13

# the copy constructor

This topic is 3969 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I was reading something on wikipedia about the copy constructor and I came accross this example.
#include <iostream>

class Array
{
public:
int size;
int* data;

Array(int size)
: size(size), data(new int[size]) {}

~Array() {
delete[] data;
}
};

int main()
{
Array first(20);
first.data[0] = 25;

{
Array copy = first;

std::cout << first.data[0] << " " << copy.data[0] << std::endl;

}    // (1)

first.data[0] = 10;    // (2)
}


according to the article the destructor is called when it reaches //(1) and when you try to execute //(2) it produces a segmentation fault. From my understanding of the situation everything seems right so I decided to try the code out using Dev-c++ and the program ran fine. There was no segmentaion fault and in fact I was able to add something like the following after //(2) and the program still worked:
//add some numbers to memory which shouldn't exist
for(int i = 0; i < 20; i++)
{
first.data = i + 1;
}

//print those numbers out
for(int i = 0; i < 20; i++)
{
cout << first.data << endl;
}


The destructor is definitely called and the memory is deleted so why are you still able to access and use it? Is the article wrong in any way?

##### Share on other sites
No, the Wikipedia article is correct. You have entered the realm of Undefined Behaviour <tm>.

Basically what really happens is that although the memory has been freed, it's still actually there as long as not enough is freed so the relevant chunk of memory is returned to the OS (how this works exactly depends on your OS/compiler/C library). So while the code will compile and may even work, it's certainly BAD, particularly because there's a good chance if you create a second array of the same size just after (1), it'll get the same memory.

##### Share on other sites
Thanks for the reply - I always find it strange when little things like this don't turn out as expected, maybe what you wrote should be added to the wikipedia article too for completeness.

##### Share on other sites
Better phrasing would be:

// (2) it may produce a segmentation fault (or other symptom of undefined behavior)