20
Aug
10

beware of copy constructor

I ran into a simple C++ problem recently. The application I was developing uses core library from C API. There are many C objects flow around, managed through pointers, alloc/free. For ease of development, I wrap a few C objects related to one process into this C++ class, with constructors to call C functions to load resources, and destructor to call C functions to free them. For multiple process in application, I choose vector to store instances of this class for each process. So I did: vector.push_back(Class(input)). The immediately I ran into problems. What happened is: when I call vector.push_back, a temporal instance is constructed, memory is allocated, then default copy constructor constructs a new instance in vector with member data copied from temporal instance, after that, the temporal instance is destructed. The instance in vector has pointers but the C object have been freed by temporal objects. The solution to this problem is to make the C++ class non-copiable by declare private copy constructors; or use shared pointers with C objects.

Advertisements

0 Responses to “beware of copy constructor”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: