The Google Style Guide for C++ says, in the section about smart pointers:
- We prefer designs in which objects have single, fixed owners.
I don’t fully understand the sentence.
- What is the object owner?
- Is it just the pointer?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The ‘owner’ of an object is not an actual part of the C++ language, but rather a conceptual tool – the idea being the ‘owner’ is in charge of deciding when the object can be destroyed. If an object has a single owner, it’s easy to figure out when the object needs to be destroyed – just look at the owner. When an object is referenced by multiple other objects, however, things are less clear – none of the referring objects can, on its own, delete the referee object, as this would cause problems for the other referers. So there there is no “single, fixed owner”.
To give some examples, consider a ‘picture’ object.
Picture does not own
rawData; as we can see from the copy constructor, it’s all too easy to have multiple Pictures referencing the same data. A better version might look like:This is similar, but now vector is hiding the raw pointer for us; it’s impossible to have two
Picturesreference the same pointer. And we take care of destroying the rawData array when the Picture is destroyed. In this case, the Picture owns the raw data.Now, you don’t have to use STL containers to have an owned object. You could do it manually:
This is also an owning relationship; the rawData array ‘belongs’ to the picture object, permanently. All accesses go through the picture object, and it’s destroyed along with the picture object.
In general, with owning relationships, it’s recommended to use wrapper classes to automate destruction, and prevent accidental copying. In my third example, had I forgotten the copy constructor or
operator=, for example, terrible things would happen. Using wrapper classes likestd::unique_ptr,boost::scoped_ptr/boost::scoped_array, orstd::vector(for owned arrays) help prevent you from making mistakes.