Archive for the 'C++' Category


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.