auto_ptr uses a dirty trick.
I use a class called auto_int to demonstrate only the functionality of building a copy without any complexity introduced by templates or inheritance. I think the code is mostly correct, but it has not been verified. Our main auto_int looks something like this:
class auto_int { public: auto_int(int* p = 0) : p_(p) { } ~auto_int() { delete p_; }
With this basic auto_int we cannot copy a temporary object. Our goal is to write something like:
auto_int p(auto_int(new int()));
What we can do is use a helper class. For auto_ptr this is called auto_ptr_ref . We will call our auto_int_ref :
class auto_int; class auto_int_ref { public: auto_int_ref(auto_int* p) : p_(p) { } auto_int& ref() { return *p_; } private: auto_int* p_; };
Basically, an instance of this class simply stores a pointer to auto_int and allows us to use it as a reference to auto_int .
Then in our auto_int class we need two additional functions. We need another constructor that accepts auto_int_ref , and we need a conversion operator that allows auto_int implicitly convert to auto_int_ref :
auto_int(auto_int_ref other) : p_(other.ref().release()) { } operator auto_int_ref() { return this; }
This will allow us to โcopyโ the temporary object while still having the copy constructor using a non-constant reference. If we look again at our sample code:
auto_int p(auto_int(new int()));
What happens, we build a new temporary auto_int and pass new int() constructor, which takes int* . This temporary expression is then converted to auto_int_ref , which points to it using the constructor operator auto_int_ref() and auto_int , which takes the value auto_int_ref , is used to initialize p .
James McNellis
source share