mardi 21 avril 2020

Segmentation fault in C++ delegating constructor

In my code, I've got this couple of constructor for the class Cli:

Cli(std::unique_ptr<Menu>&& _rootMenu,
    std::function< void(std::ostream&)> _exitAction = {},
    std::unique_ptr<HistoryStorage>&& historyStorage = std::make_unique<LocalHistoryStorage>()
) :
    globalHistoryStorage(std::move(historyStorage)),
    rootMenu(std::move(_rootMenu)),
    exitAction(_exitAction)
{
}

#if 0 // (1) crash at run-time
Cli(std::unique_ptr<Menu>&& _rootMenu, std::unique_ptr<HistoryStorage>&& historyStorage) : 
    Cli(std::move(rootMenu), {}, std::move(historyStorage))
{
}
#else // (2) this works
Cli(std::unique_ptr<Menu>&& _rootMenu, std::unique_ptr<HistoryStorage>&& historyStorage) :
    globalHistoryStorage(std::move(historyStorage)),
    rootMenu(std::move(_rootMenu)),
    exitAction(nullptr)
{
}
#endif

When I construct the object with:

Cli cli(std::move(rootMenu), std::make_unique<FileHistoryStorage>());

I get a segmentation fault at runtime if I use the delegating constructor (1). However, it works with the constructor (2).

Where am I wrong?

Thanks

Aucun commentaire:

Enregistrer un commentaire