复制和直接初始化背后的动机有什么不同? [英] What's the motivation behind having copy and direct initialization behave differently?
问题描述
初始化,直接和复制初始化有两种语法:
There are two syntaxes for initialization, direct- and copy-initialization:
A a(b);
A a = b;
我想知道他们有不同定义行为的动机。对于副本初始化,涉及额外的副本,我不能想到该副本的任何目的。因为它是一个来自temp的副本,它可以并且可能会被优化,所以用户不能依赖它发生 - ergo额外的副本本身不足以为不同的行为。那么......为什么?
I want to know the motivation for them having different defined behavior. For copy initialization, an extra copy is involved, and I can't think of any purpose for that copy. Since it's a copy from a temp, it can and probably will be optimized out, so the user can't rely on it happening - ergo the extra copy itself isn't reason enough for the different behavior. So... why?
推荐答案
只是一个猜测,但恐怕很难更确定没有Bjarne Stroustrup确认它是如何是真的:
Only a speculation, but I am afraid it will be hard to be more certain without Bjarne Stroustrup confirming how it really was:
它是这样设计的,因为它被认为这样的行为将被程序员期望,他期望复制完成时=符号,而不是直接的初始化语法。
It was designed this way because it was assumed such behaviour will be expected by the programmer, that he will expect the copy to be done when = sign is used, and not done with the direct initializer syntax.
我认为可能的复制elision只添加在标准的更高版本,但我不知道 - 这是某人可能能够通过检查标准历史来确定。
I think the possible copy elision was only added in later versions of the standard, but I am not sure - this is something somebody may be able to tell certainly by checking the standard history.
这篇关于复制和直接初始化背后的动机有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!