How to “return an object” in C++?

后端 未结 8 550
礼貌的吻别
礼貌的吻别 2020-11-22 09:25

I know the title sounds familiar as there are many similar questions, but I\'m asking for a different aspect of the problem (I know the difference between having things on t

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 09:36

    Firstly you have an error in the code, you mean to have Thing *thing(new Thing());, and only return thing;.

    • Use shared_ptr. Deref it as tho it was a pointer. It will be deleted for you when the last reference to the Thing contained goes out of scope.
    • The first solution is very common in naive libraries. It has some performance, and syntactical overhead, avoid it if possible
    • Use the second solution only if you can guarantee no exceptions will be thrown, or when performance is absolutely critical (you will be interfacing with C or assembly before this even becomes relevant).

提交回复
热议问题