Is make_shared really more efficient than new?

前端 未结 4 1654
花落未央
花落未央 2020-12-02 08:56

I was experimenting with shared_ptr and make_shared from C++11 and programmed a little toy example to see what is actually happening when calling <

4条回答
  •  情深已故
    2020-12-02 09:45

    You should not be getting any extra copies there. The output should be:

    Create smart_ptr using make_shared...
    Constructor make_shared
    Create smart_ptr using make_shared: done.
    Create smart_ptr using new...
    Constructor new
    Create smart_ptr using new: done.
    Destructor
    

    I don't know why you're getting extra copies. (though I see you're getting one 'Destructor' too many, so the code you used to get your output must be different from the code you posted)

    make_shared is more efficient because it can be implemented using only one dynamic allocation instead of two, and because it needs one pointer's worth of memory less book-keeping per shared object.

    Edit: I didn't check with Xcode 4.2 but with Xcode 4.3 I get the correct output I show above, not the incorrect output shown in the question.

提交回复
热议问题