M
Marijn
Say i have an object that represents or holds a resource like an open
file, a block of memory on the heap, or an openGL texture object. The
constructor acquires the resource, and the destructor releases it. I
want to implement efficient copying and assignment for this object -
the copy constructor passes on the 'handle' (file pointer, memory
pointer, or opengl texture id) to the new object, and invalidates the
old object. I guess this is how the std::auto_ptr works too. I can
come up with several ways to do this, but i'd like to see how it
usually done, since i guess this is a quite common problem and people
will undoubtedly have come up with a brilliant solution.
Possible method: Have a boolean valid flag in the object, all methods
that require the resource check this flag and report error when the
object is not valid. Destructor only releases the resource if the
object is valid. The copy constructor and assignment operator set this
flag to false in the original object and copy the handle variable
instead of initalizing their own resource. Is this The Way To Do It,
or does it have flaws?
Marijn Haverbeke
file, a block of memory on the heap, or an openGL texture object. The
constructor acquires the resource, and the destructor releases it. I
want to implement efficient copying and assignment for this object -
the copy constructor passes on the 'handle' (file pointer, memory
pointer, or opengl texture id) to the new object, and invalidates the
old object. I guess this is how the std::auto_ptr works too. I can
come up with several ways to do this, but i'd like to see how it
usually done, since i guess this is a quite common problem and people
will undoubtedly have come up with a brilliant solution.
Possible method: Have a boolean valid flag in the object, all methods
that require the resource check this flag and report error when the
object is not valid. Destructor only releases the resource if the
object is valid. The copy constructor and assignment operator set this
flag to false in the original object and copy the handle variable
instead of initalizing their own resource. Is this The Way To Do It,
or does it have flaws?
Marijn Haverbeke