Sign in to follow this  

the copy constructor

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

If you intended to correct an error in the post then please contact us.

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] = i + 1;
    }
  
//print those numbers out    
    for(int i = 0; i < 20; i++)
    {
            cout << first.data[i] << 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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this