Why is it better to use std::make_* instead of the constructor?

前端 未结 3 981
我在风中等你
我在风中等你 2021-02-18 16:56

There are some functions in the STL which start with the make_ prefix like std::make_pair, std::make_shared, std::make_unique

3条回答
  •  梦毁少年i
    2021-02-18 17:21

    Although it may be subjective, one main touted benefit for this technique is:

    write code against interfaces, not implementations

    In essence, function template instantiation performs type deduction based on the arguments you pass, whereas class template instantiation does not. As a consequence, you wouldn't have to pass template arguments as you would when instantiating the class directly.

    It should be noted though, that this is not about "saving a few characters", but rather about making your code more general, and avoiding being tied to a concrete type in your function call.

    However, this is not always the case, as your std::make_shared example showed, there are still cases in which you have to pass the type as a template argument. But, as Herb Sutter points out, there are several other advantages when it comes to using std::make_shared:

    1. You should write for clarity and correctness first, and std::make_shared achieves both of those (subjective, but I agree)

    2. using std::make_shared is more efficient, because it allocates your object as well as the shared_ptr object in one go, allowing for lower allocation overhead and a likely better cache alignment.

提交回复
热议问题