2

Say for instance I have the prototype:

QList<Foo *> *methodBar(int someParam);

This method returns a QList pointer to the client code - how does the client code know if it needs to destroy the returned pointer?

Is there a convention that says if you are given a pointer it's your business to control it's memory? Or vice versa?

My thoughts to solve this are:

Option 1: Document it in the doc block that the client code has to get rid of the QList once it is done with it.

Option 2 Change the signature to something like:

void methodBar(int someParam, QList<Foo *> &listForOutput);

So that the client code creates the list and definitely knows that it should destroy it when it is finished.

Option 3 Use some kind of smart pointer, I'm not sure if this works but if I wrapped a QList* inside a QPointer and returned a copy of the QPointer I assume it would shallow copy the internal QList* and then when the QPointer went out of scope in the client code it would be destroyed along with the QList*.

So which of these options (or perhaps something else?) is the most common in the c++ world. If there is no standard way of doing this I'll accept an answer that it is up to personal preference.

4

1 回答 1

4

如果您希望调用者知道他们对指针负责,请使用以下命令:

std::unique_ptr<QList<Foo *>> methodBar(int someParam);

另一个优点是调用者必须竭尽全力使内存不会被自动释放。

Astd::unique_ptr不能被复制,只能移动,因此std::unique_ptr相当明确地传递 a 会导致释放内存的责任从被调用者移动到调用者。

请注意,这也意味着列表内指向的对象不是调用者的责任。如果您希望这些对象也由调用者负责,您可以使用:

std::unique_ptr<QList<std::unique_ptr<Foo>>> methodBar(int someParam);
于 2013-06-09T18:45:52.763 回答