Jump to content
  • Advertisement
Sign in to follow this  
popcorn

the copy constructor

This topic is 4091 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 + 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 this post


Link to post
Share on other sites
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!