Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

member taking ownership of parameter

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?

like image 656
fredoverflow Avatar asked Jul 09 '12 13:07

fredoverflow


1 Answers

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.

like image 110
Puppy Avatar answered Oct 02 '22 00:10

Puppy