1

I have a class named Texture that has a pointer to a SDL_Surface. When I want to add it to a vector I need to have a non-default copy constructor to prevent problems when the original goes out of scope. I know that the copy constructor is called whenever the object is passed by value to a function. Will passing many Texture objects by value to my render function every frame cause my program to slow down? I know I can pass by reference to avoid this problem but I would like to keep my existing code as is if possible.

Alidaco
  • 171
  • 1
  • 8
  • 1
    Why don't you measure it and tell us? – Sergio Tulentsev Dec 21 '11 at 06:17
  • How intense is the explicit copy constructor? The most room for managing performance is to have an explicit copy constructor. There is nothing magic about the default. – wallyk Dec 21 '11 at 06:18
  • Sure, I was just hoping to know before I went to write my code. Also, when I create my copy constructor do I have to initialize all of the variables or just the pointers. If I just work with the pointers will the rest be copied automatically? – Alidaco Dec 21 '11 at 06:19
  • 2
    If you write your own copy constructor, you must take care of *everything* since the default one won't even be generated. – Greg Hewgill Dec 21 '11 at 06:21
  • I wouldn't be worried normally but I have to call IMG_Load on the SDL_Surface every time it is copied. I want to avoid that overhead. – Alidaco Dec 21 '11 at 06:21
  • Thanks for the quick response Greg. – Alidaco Dec 21 '11 at 06:21

1 Answers1

2

First of all, if you are really concerned about performance, then you should be passing references around, passing by value could get very expensive, no matter if you use the default or a custom copy constructor.

Now, if you are completely set on passing stuff by value and using copy constructors, I think the default copy constructor is nice, because it takes care of everything for you. You should try to adapt your class so that you can continue using it, if possible.

If your class has pointers, then one approach is to wrap them inside some kind of smart pointer. For example, if instead of SDL_Surface* you use std::shared_ptr<SDL_Surface> (or boost::shared_ptr<SDL_Surface> which is the same) then you enable that pointer to be copied. The shared_ptr class will keep a reference count on it and only delete the surface when all the references are gone. Note that if you do this approach you need to use a custom delete function for SDL_Surface, as shown in this question.

Community
  • 1
  • 1
Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152