我已经问过a similar question前段时间,但我仍然不清楚一些细节。
最佳答案
swap
有多种不同的情况。如果你想让它尽可能高效,函数就不得不担心。我建议只使用 swap function in std.algorithm .经典的交换会导致复制,因此会调用 postblit 构造函数和析构函数。 move 通常由编译器完成,而不是程序员。然而,looking at the official implementation的 swap
,看起来它玩了一些技巧来尽可能地将 move 语义排除在外。无论如何, move 通常由编译器完成。它们是一种优化,它将在它知道可以做到的地方进行(RVO 是它可以做到的经典案例)。 根据 TDPL (p. 251),只有两种情况 D 保证 move 会发生:
- All anonymous rvalues are moved, not copied. A call to
this(this
) is never inserted when the source is an anonymous rvalue (i.e., a temporary as featured in the functionhun
above).- All named temporaries that are stack-allocated inside a function and then returned elide a call to
this(this)
.- There is no guarantee that other potential elisions are observed.
因此,编译器可能会在其他地方使用 move ,但不能保证它会这样做。
关于templates - 关于 postblit 和 move 语义的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6884996/