Well-designed memory ownership

What does well-designed memory ownership look like? The naive answer that first comes up is that, at every point in the program, it is clear who owns what object. This, however, is overly constraining—most of the program does not deal with ownership of resources, including memory. These parts of the program merely use resources. When writing such code, it is sufficient to know that a particular function or class does not own the memory. It is completely irrelevant to know who does what:

struct MyValues { long a, b, c, d; }
void Reset(MyValues* v) { // Don't care who owns v, as long as we don't
v->a = v->b = v->c = v->d = 0;
}

How about this, then—at every point in the program, is it clear who owns that object, or is it clear that the ownership is not changing? This is better, since most of the code will fall under the second part of our answer. However, it's still too constraining—when taking ownership of an object, it is usually not important to know who it is taken from:

class A {
public:
A(std::vector<int>&& v) :
v_(std::move(v)) {} // Transfers ownership from whomever
private:
std::vector<int> v_; // We own this now
};

Similarly, the whole point of the shared ownership (expressed through the reference-counted std::shared_ptr) is that we don't need to know who else owns the object:

class A {
public:
A(std::shared_ptr<std::vector<int>> v) : v_(v) {}
// No idea who owns v, don't care
private:
std::shared_ptr<std::vector<int>> v_;
// Sharing ownership with any number of owners
};

A more accurate description of well-designed memory ownership takes more than one quoted sentence. Generally, the following are the attributes of good memory ownership practices:

  • If a function or a class does not alter memory ownership in any way, this should be clear to every client of this function or class, as well as the implementer
  • If a function or a class takes exclusive ownership of some of the objects passed to it, this should be clear to the client (we assume that the implementer knows this already, since he/she has to write the code)
  • If a function or a class shares ownership of an object passed to it, this should be clear to the client (or anyone who reads the client code, for that matter)
  • For every object that is created, at every point that it's used, it is clear whether this code is expected to delete it or not
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.24.60