Question

I see two reasonable solutions to the problem of a member taking ownership of a parameter:

Foo::Foo(std::unique_ptr<int> parameter)
: member(std::move(parameter))
{
}

Bar::Bar(std::unique_ptr<int> parameter)
{
    member.swap(parameter);
}

Which of these is more idiomatic, easier to understand, easier to debug, easier to maintain etc.?

Are there additional solutions to the problem that I've missed?

Was it helpful?

Solution

Always favour initializer list. In addition, it covers types which can be moved but not swapped, for example, or types which may have to perform expensive operations for default construction- or indeed, types which simply cannot be default constructed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top