Search code examples
c++shared-ptrsmart-pointersunique-ptr

Why make_unique and make_shared uses parenthesis and not curly braces?


I.e. all implementations of the Standard Library (in MSVC, clang, gcc) use the following code (simplified for readability):

template<class T, class... Args>
inline unique_ptr<T> make_unique(Args&&... args)
{
    return unique_ptr<T>(new T(std::forward<Args>(args)...));
}

But why not curly braces? I.e.:

template<class T, class... Args>
inline unique_ptr<T> make_unique(Args&&... args)
{
    return unique_ptr<T>(new T{std::forward<Args>(args)...});
    //                        ^ here and                  ^ here
}

(Same question for make_shared.)


Solution

  • Because those 2 implementations will behave differently in certain cases. The standard library must choose one of the semantics to make it consistent.

    #include <memory>
    #include <vector>
    #include <iostream>
    
    template<class T, class... Args>
    inline std::unique_ptr<T> my_make_unique(Args&&... args)
    {
        return std::unique_ptr<T>(new T{std::forward<Args>(args)...});
    }
    
    int main() {
        auto a = std::make_unique<std::vector<int>>(12);
        std::cout << a->size() << "\n";
    
        auto b = my_make_unique<std::vector<int>>(12);
        std::cout << b->size() << "\n";
    }
    

    Here a is a vector of size 12, b is a vector of size 1 whose value is 12.