Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Considerations about move semantic for a type

Tags:

c++

c++11

I am implementing a type T. Although this is not a requirement, users of this type may benefit from move semantic, that is T(T&&) and T& operator=(T&&).

Since T contains std::function's as member data, I cannot implement move semantic with the noexcept guarantees, which would make T less useful for the user.

Also, for the above reason, my implementation cannot be as simple as: T(&&) noexcept = default and T& operator=(T&&) noexcept = default

The alternative would be to either offer the user the non-noexcept versions: T(&&) = default and T& operator=(T&&) = default; or implement my user defined noexcept move semantic in terms of std::function::swap() (which is guaranteed to be noexcept). In the latter case, I would unfortunately have to take care of all the other member data other than std::function's (ugly!).

So, there are three options:

  1. disable move semantic at all
  2. implement T(&&) = default and T& operator=(T&&) = default
  3. implement my own T(&&) noexcept {/* lot of code */} and T& operator=(T&&) noexcept {/* lot of code */}

I know the question is rather subjective, but What would you opt for?

like image 265
Martin Avatar asked Sep 27 '22 23:09

Martin


1 Answers

Assuming you really want the noexcept move, you can reduce the amount of boilerplate for option #3 by either:

  1. grouping the default-noexcept-moveable members into a nested struct member or private base class, and write a move-ctor which simply moves that (one line for all of them), and then swaps the std::functions, or
  2. writing a SwapMove template wrapper for storing a function in. It just needs to implement the move ctor and assignment operator using swap, and default everything else. OK, you'll also need to either expose the function member or forward the function call operator.
like image 109
Useless Avatar answered Oct 04 '22 17:10

Useless