Are there any use cases for a class which is copyable but not movable?

前端 未结 5 1569
名媛妹妹
名媛妹妹 2020-12-18 20:22

After reading this recent question by @Mehrdad on which classes should be made non-movable and therefore non-copyable, I starting wondering if there are use

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-18 21:02

    It depends on how you define the semantics of the move operation for your type. If move merely means optimized copy through resource-stealing then the answer is probably no. But the answer might be yes if move means "relocate" in the sense used by a moving garbage collector or some other custom memory management scheme.

    Consider a real-world example of a house located on a particular street address. One can define a copy of that house to be another house built using the exact same blueprints, but located on another address. Under these terms, we can go on saying that a house cannot be moved, because there might be people referring to it by its address. Translating to technical terms, the move operation might not be possible for structures that have inbound pointers.

    I can imagine a bit twisted implementation of a signals/slots library that allows its signals objects to be copied, but doesn't allow them to be moved.

    disclaimer: some C++ purists will point out that STL (and thus the standard) defines what a move operation is and it's not in line with what I described here so I won't argue with that.

提交回复
热议问题