templates - 关于 postblit 和 move 语义的问题

标签 templates return-value d copy-constructor move-semantics

我已经问过a similar question前段时间,但我仍然不清楚一些细节。

  • postblit 构造函数在什么情况下被调用?
  • move 对象的语义是什么?它会被 postblitted 和/或破坏吗?
  • 如果我按值返回局部变量会发生什么?它会被隐式 move 吗?
  • 如何将表达式转换为右值?例如,通用交换会是什么样子?
  • 最佳答案

  • 每当复制结构时都会调用 postblit 构造函数 - 例如将结构传递给函数时。
  • move 是按位复制。 postblit 构造函数永远不会被调用。永远不会调用析构函数。这些位被简单地复制。原件已“move ”,因此无需创建或销毁任何内容。
  • 它将被 move 。这是 move 的主要例子。
  • swap 有多种不同的情况。如果你想让它尽可能高效,函数就不得不担心。我建议只使用 swap function in std.algorithm .经典的交换会导致复制,因此会调用 postblit 构造函数和析构函数。 move 通常由编译器完成,而不是程序员。然而,looking at the official implementationswap ,看起来它玩了一些技巧来尽可能地将 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 function hun 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/

    相关文章:

    Scala Play 框架 2.2 - 如何在模板中获取有关用户登录状态的信息

    带有纯虚函数的C++模板返回值

    c++ - 如何返回一维大小未知的二维数组?

    metaprogramming - D对这些功能是否足够强大?

    c++ - 嵌套模板特化

    c - 处理函数错误消息的最佳方式?

    python - 我们如何检查函数是否在 Python 中返回多个值?

    c# - D 中 C# `readonly` 关键字的等价物?

    dlang如何让dub找到外部库

    c++ - 多个容器和数据类型的模板函数