I am developing a noSQL database and currently moving the code from C to C++.
It have class Pair, which contains a raw pointer to a memory blob.
class Pair {
Blob* blob;
...
};
Then if you add this Pair to the List class, the List class stores this raw pointer internally, without copying. In order not to leak memory, the List notifies the Pair not to delete the raw pointer.
class Pair {
Blob* _blob;
bool _owns_blob;
public:
Pair(Blob* blob, bool owns_blob = true)
: _blob(blob), _owns_blob(owns_blob) {}
~Pair() { if (_owns_blob) delete _blob; }
...
Blob* blob() { return _blob; }
void disown() { _owns_blob = false; }
};
void List::put(Pair& p) {
store_blob(p.blob());
p.disown();
}
Because of this notification, I can not use a method signature like this:
List.put(const Pair &p)
and I will need to pass by value or by non-const reference.
Later if you request the data, the program creates a new Pair and includes the raw pointer inside, and also instructs the Pair not to delete the pointer:
Pair List::get(...) {
return Pair(get_blob(), false);
}
Would this model benefit from shared pointers? How would this affect the speed and memory consumption?
Pairto aListcauses theListto consume (take away) the ownership of the blob from thePair. As a result thePairdoes not own the blob anymore.