When will adding a move constructor and a move assignment operator really start make a difference?

前端 未结 5 752
没有蜡笔的小新
没有蜡笔的小新 2021-01-05 21:11

Considering the high quality of today\'s compilers regarding return value optimization (both RVO and NRVO), I was wondering at what class complexity it\'s actually meaningfu

5条回答
  •  被撕碎了的回忆
    2021-01-05 21:34

    As a rule of thumb I would say add a move constructor whenever you have member variables which hold (conditionally) dynamically allocated memory. In that case its often cheaper if you can just use the existing memory and give the move source the minimal allocation it needs so it can still function (meaning be destroyed). The amount of member variables doesn't matter that much, because for types not involving dynamic memory its unlikely to make a difference whether you copy or move them (even the move constructor will have to copy them from one memory location to another somehow).

    Therefore move semantices make sense, when

    • dynamic memory allocation is involved
    • move makes sense for one or more member variables (which means those involve dynamic allocation somewhere along the line).

提交回复
热议问题