Is make_shared really more efficient than new?

前端 未结 4 1659
花落未央
花落未央 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 10:00

    As infrastructure I was using llvm/clang 3.0 along with the llvm std c++ library within XCode4.

    Well that appears to be your problem. The C++11 standard states the following requirements for make_shared (and allocate_shared), in section 20.7.2.2.6:

    Requires: The expression ::new (pv) T(std::forward(args)...), where pv has type void* and points to storage suitable to hold an object of type T, shall be well formed. A shall be an allocator (17.6.3.5). The copy constructor and destructor of A shall not throw exceptions.

    T is not required to be copy-constructable. Indeed, T isn't even required to be non-placement-new constructable. It is only required to be constructable in-place. This means that the only thing that make_shared can do with T is new it in-place.

    So the results you get are not consistent with the standard. LLVM's libc++ is broken in this regard. File a bug report.

    For reference, here's what happened when I took your code into VC2010:

    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
    Destructor
    

    I also ported it to Boost's original shared_ptr and make_shared, and I got the same thing as VC2010.

    I'd suggest filing a bug report, as libc++'s behavior is broken.

提交回复
热议问题