Is there any general convention for ownership of pointers when passing pointers as parameter or returning it as return value?

19 views
Skip to first unread message

Stephen Cheng

unread,
Jul 15, 2013, 10:00:00 PM7/15/13
to chromi...@chromium.org
I found that in many of the function definitions, it's not exactly clear from the brief comment about who actually owns the pointer (and is responsible for deleting the pointer) when passing pointers as parameter or returning it as return value. Is there any general convention or assumption about it?
 
Here is an example:
 
const DictionaryValue *PrefService::GetDictionary(const char *path)
 
It returns a DictionaryValue pointer. Should be the caller delete the returned pointer once it is done with it?

Rachel Blum

unread,
Jul 15, 2013, 10:18:00 PM7/15/13
to Shanfeng Cheng, Chromium-dev
In general, if there's no comment, assume the callee keeps ownership of any const* it returns. Especially if the function is named GetXXX.


--
--
Chromium Developers mailing list: chromi...@chromium.org
View archives, change email options, or unsubscribe:
http://groups.google.com/a/chromium.org/group/chromium-dev
 
 
 

Jonathan Dixon

unread,
Jul 15, 2013, 10:26:03 PM7/15/13
to Rachel Blum, Shanfeng Cheng, Chromium-dev
For new code, the tendency is to prefer scoped_ptr<> to document (and enforce) ownership transfers. So by extension, if you know you're reading "new code" (i.e. that has a bunch of pass-by-value scoped_ptr going on elsewhere) then you can make broader assumptions that naked Foo* is not transferring ownership, regardless of const-ness.

(My own code-reviewing habit is to always ask for a comment on the raw pointer case though.)


And of course if 'Foo' is ref-counted, ignore all this and read it again applying ref-counting semantics to your deductions :-)


Peter Kasting

unread,
Jul 16, 2013, 12:15:16 AM7/16/13
to sfc...@gmail.com, Chromium-dev
On Mon, Jul 15, 2013 at 7:00 PM, Stephen Cheng <sfc...@gmail.com> wrote:
Here is an example:
 
const DictionaryValue *PrefService::GetDictionary(const char *path)
 
It returns a DictionaryValue pointer. Should be the caller delete the returned pointer once it is done with it?

In general, work toward making code take or return scoped_ptrs when ownership is being passed, and use raw pointers only when ownership is not passed.  Certainly new code people write should do this as much as possible.  Old code should be converted opportunistically.

In addition, I suggest explicitly documenting the ownership model anywhere a raw pointer is used.  The amount of code that does _not_ use scoped_ptrs to indicate ownership transfer is unfortunately "most of Chromium" right now, so readers who see raw pointers can't really assume anything.  Thus the need for comments.

PK
Reply all
Reply to author
Forward
0 new messages