I want a safe C++ pointer container similar to boost's scoped_ptr, but with value-like copy semantics. I intend to use this for a very-rarely used element of very-heavily used class in the innermost loop of an application to gain better memory locality. In other words, I don't care about performance of this class so long as its "in-line" memory load is small.
I've started out with the following, but I'm not that adept at this; is the following safe? Am I reinventing the wheel and if so, where should I look?
template <typename T> class copy_ptr { T* item; public: explicit copy_ptr() : item(0) {} explicit copy_ptr(T const& existingItem) : item(new T(existingItem)) {} copy_ptr(copy_ptr<T> const & other) : item(new T(*other.item)) {} ~copy_ptr() { delete item;item=0;} T * get() const {return item;} T & operator*() const {return *item;} T * operator->() const {return item;} }; Edit: yes, it's intentional that this behaves pretty much exactly like a normal value. Profiling shows that the algorithm is otherwise fairly efficient but is sometimes hampered by cache misses. As such, I'm trying to reduce the size of the object by extracting large blobs that are currently included by value but aren't actually used in the innermost loops. I'd prefer to do that without semantic changes - a simple template wrapper would be ideal.
while(true){ loopUsingHeavyObjectOnly(); loopUsingEverythingButHeavyObject(); }