gpt4 book ai didi

c++ - 我会得到这个初始化的拷贝或作业吗?

转载 作者:太空狗 更新时间:2023-10-29 20:14:46 25 4
gpt4 key购买 nike

比较 C++ 中的这两种初始化方法,用于一个普通的复数类。

complx one(1,3);
complx two = complx(3,4);

在第二种情况下,我会得到一个构造函数,然后是一个赋值,然后是一个拷贝,还是只是构造函数?

是否可以区分这两种类型的初始化?

最佳答案

complx two = complx(3,4);

这是一个复制初始化。这条规则涵盖了这个初始化器的特定语义:

If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as [...] the class of the destination, constructors are considered. The applicable constructors are enumerated (13.3.1.3), and the best one is chosen through overload resolution (13.3). The constructor so selected is called to initialize the object, with the initializer expression or expression-list as its argument(s). [...]

也就是说,源类型与目标类型相同的复制初始化的行为类似于直接初始化。所以这使得声明等同于:

complx two(complx(3,4));

这构造了一个临时的 complx 对象,然后使用复制/移动构造函数构造了 two

但是,此复制/移动可能会被省略:

when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

但是,复制构造函数必须仍可访问,因为尽管它正在被调用。

这两个初始化能区分吗?假设复制/移动是有效的,但不可靠,不。如果编译器确实在复制初始化中省略了拷贝,或者如果拷贝表现良好并且没有任何额外的副作用,那么两者的行为将完全相同。如果它没有消除拷贝并且拷贝有一些额外的副作用,那么您会注意到不同之处。

关于c++ - 我会得到这个初始化的拷贝或作业吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15412762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com