关于postblit和move语义的问题 [英] Questions about postblit and move semantics

查看:123
本文介绍了关于postblit和move语义的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前段时间我已经问过类似的问题,但是我仍然不清楚一些细节.

I have already asked a similar question a while ago, but I'm still unclear on some details.

  1. 在什么情况下,postblit构造函数被称为?

  1. Under what circumstances is the postblit constructor called?

移动对象的语义是什么?它会被过时和/或破坏吗?

What are the semantics of moving an object? Will it be postblitted and/or destructed?

如果我按值返回局部变量会怎样?会隐式地移动吗?

What happens if I return a local variable by value? Will it implicitly be moved?

如何将表达式强制转换为右值?例如,通用交换的外观如何?

How do I cast an expression to an rvalue? For example, how would a generic swap look like?

推荐答案

  1. 每当复制结构时都会调用postblit构造函数-例如将结构传递给函数时.

  1. A postblit constructor is called whenever the struct is copied - e.g. when passing a struct to a function.

移动是按位复制. postblit构造函数从不调用.永远不会调用析构函数.这些位被简单地复制.原始文件已移动",因此无需创建或销毁任何内容.

A move is a bitwise copy. The postblit constructor is never called. The destructor is never called. The bits are simply copied. The original was "moved" and so nothing needs to be created or destroyed.

它将被移动.这是举动的典型例子.

It will be moved. This is the prime example of a move.

swap函数在很多情况下都需要担心,如果您想使其尽可能高效.我建议仅在std.algorithm 中使用 swap函数.经典交换将导致复制,因此将调用postblit构造函数和析构函数.移动通常是由编译器完成的,而不是由程序员完成的.但是,查看正式实施情况swap的a>,它似乎起到了一些技巧,可以尽可能地使语义脱离交易.无论如何,移动通常是由编译器完成的.它们是一种优化,它将在它知道的地方进行( RVO 是经典案例可以).

There are a number of different situations that a swap function would have to worry about if you want to make it as efficient as possible. I would advise simply using the swap function in std.algorithm. The classic swap would result in copying and would thus call the postblit constructor and the destructor. Moves are generally done by the compiler, not the programmer. However, looking at the official implementation of swap, it looks like it plays some tricks to get move semantics out of the deal where it can. Regardless, moves are generally done by the compiler. They're an optimization that it will do where it knows that it can (RVO being the classic case where it can).

根据 TDPL (第251页),只有2种情况D 保证会采取行动:

According to TDPL (p. 251), there are only 2 cases where D guarantees that a move will take place:

  • 所有匿名右值被移动,而不是被复制.呼叫this(this) 当来源是匿名右值(即 临时功能,如上面的功能hun所示).
  • 所有在函数内部堆栈分配的命名临时变量, 然后返回取消呼叫this(this).
  • 不能保证观察到其他潜在的清除.
  • 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,但是并不能保证会使用

So, the compiler may use moves elsewhere, but there's no guarantee that it will.

这篇关于关于postblit和move语义的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆