using c++ aggregate initialization in std::make_shared

后端 未结 2 1805
抹茶落季
抹茶落季 2020-12-05 13:58

Per my understanding, the following code constructs an object of type Foo and then moves that object into the memory allocated by std::make_shared<

2条回答
  •  一整个雨季
    2020-12-05 14:39

    You could create an adapter with a variadic constructor template to forward the arguments, something like:

    template
    struct aggregate_adapter : public T {
        template
        aggregate_adapter(Args&&... args) : T{ std::forward(args)... } {}
    };
    

    And then you can do:

    auto foo = std::make_shared>("hello", 5, 'c');
    

    Since aggregate_adapter and Foo are related, foo is convertible to std::shared_ptr as well.

    Caveats


    Unfortunately, the use of forwarding also makes it impossible to brace-init any of the members like std::make_shared>({'h','e','l','l','o'}, 5, 'c'); without specifying the type explicitly, but the same restriction applies to make_shared already.

提交回复
热议问题