-1

For instance, if I were to have a game where I wanted bouncing dots within the screen, assuming that the dots were put into a list upon construction and the rendering and movement were handled, could I do this in main without shallow copies being made.

int main()
{ 
    for(int i = 0; i < 10; i++)
    {
        Dot * temp = new Dot();
    }

    while(!quit)
    {    
        //Handle the dot rendering and movement
    }
}

I ask this because I did do something very similar and, whenever I attempted to remove the Dots in the list if they hit one another, after one Dot was deleted and I attempted to delete another I got a Segmentation Fault. Thanks in advance!

  • 2
    Since `Dot` is not defined, this code is obviously not producing any problems. Show some real code that compiles and runs and demonstrates the problem you're having. – Pete Becker Mar 17 '13 at 21:34
  • This code leaks 10 `Dot`s. Please provide a [Short, Self Contained, Correct (Compilable), Example](http://sscce.org/) that demonstrates your actual problem. (See [Writing the perfect question](http://tinyurl.com/so-hints) for more hints on getting good answers). – johnsyweb Mar 17 '13 at 21:46

2 Answers2

1

It sounds like your previous problem was double-deleting. If Dot has a destructor, and in that destructor you delete one or more pointers to member objects, then you definitely want a copy constructor. The default copy constructor would leave two Dots with pointers to the same objects, and then when both Dots were deleted, the child pointers would be deleted twice. That is certainly illegal, and often leads to segfaults. You need to provide a copy constructor that provides each Dot with its own child objects, so double-deleting doesn't happen.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
1

@Ernest is right, Segmentation fault isn't due to copy constructor, but to your attempt to access / delete a memory location which you can't access. It means the pointer you're using is pointing to a bad memory adress, and it can be because you've already deleted it.

The copy constructor has nothing to see whether the object is 'new' or not. Anyway, a dumb copy constructor is generally generated if you don't implement one (Conditions for automatic generation of default/copy/move ctor and copy/move assignment operator?).

"Dumb" means, the class won't be able to copy automatically all the classes instances created with new for example, or more generally, pointed elements.

The destructor is called at the end of the scope, or when you call the 'delete' operator on 'new' object (dynamically allocated memory). Same, a dumb destructor is automatically implemented by most of the c++ compilers.

"Dumb" means, the class won't delete automatically all the variables created with 'new'.

Check this for completness : What is The Rule of Three?

Community
  • 1
  • 1
Touki
  • 833
  • 2
  • 9
  • 20