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.
Share
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 usestd::shared_ptr<SDL_Surface>(orboost::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.