Why have move semantics?

后端 未结 4 806
鱼传尺愫
鱼传尺愫 2021-02-12 19:24

Let me preface by saying that I have read some of the many questions already asked regarding move semantics. This question is not about how to use move semantics, it is asking w

4条回答
  •  猫巷女王i
    2021-02-12 19:51

    I thoroughly enjoyed all the answers and comments! And I agree with all of them. I just wanted to stick in one more motivation that no one has yet mentioned. This comes from N1377:

    Move semantics is mostly about performance optimization: the ability to move an expensive object from one address in memory to another, while pilfering resources of the source in order to construct the target with minimum expense.

    Move semantics already exists in the current language and library to a certain extent:

    • copy constructor elision in some contexts
    • auto_ptr "copy"
    • list::splice
    • swap on containers

    All of these operations involve transferring resources from one object (location) to another (at least conceptually). What is lacking is uniform syntax and semantics to enable generic code to move arbitrary objects (just as generic code today can copy arbitrary objects). There are several places in the standard library that would greatly benefit from the ability to move objects instead of copy them (to be discussed in depth below).

    I.e. in generic code such as vector::erase, one needs a single unified syntax to move values to plug the hole left by the erased valued. One can't use swap because that would be too expensive when the value_type is int. And one can't use copy assignment as that would be too expensive when value_type is A (the OP's A). Well, one could use copy assignment, after all we did in C++98/03, but it is ridiculously expensive.

    shouldn't all non-primitive type members be pointers to speed up movement

    This would be horribly expensive when the member type is complex. Might as well color it Java.

提交回复
热议问题