dimanche 15 mai 2022

Why `std::make_shared` does not work anymore when the class inherits class `enable_shared_from_this`? [duplicate]

Why std::make_shared does not work anymore when the class Widget inherits class enable_shared_from_this?

Here is the code snippet:

#include<memory>
#include<vector>
#include<iostream>

class Widget:public std::enable_shared_from_this<Widget>
{
public:
    std::vector<int> vec;
    int var;
};

int main()
{
    auto wp{std::make_shared<Widget>()}; 
    //auto wp1{std::make_shared<Widget>(std::vector{1,2,3}, 9)}; //why his line compiles if class Widget does not inherit class enable_shared_from_this<Widget> 
}

What's more, auto wp1{std::make_shared<Widget>(std::vector{1,2,3}, 9)}; works well if you remove the inheritance.

TED's answer:

It's because there is a constructor added by enable_shared_from_this which removes the possibility to do aggregate initialization. In order to support creating it from make_shared, add the necessary constructors:

public:
    Widget() = default;
    Widget(const std::vector<int>& v, int i) : vec(v), var(i) {}

It works indeed.But I still don't know why there is a constructor added by enable_shared_from_this?

Aucun commentaire:

Enregistrer un commentaire