加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 我是否会通过此初始化获得副本或作业?

发布时间:2020-12-16 09:43:11 所属栏目:百科 来源:网络整理
导读:比较C中的这两个初始化方法,以获得一个简单的复数类. complx one(1,3);complx two = complx(3,4); 在第二种情况下,我会得到一个构造函数,后跟一个赋值,后跟一个副本,还是只有构造函数? 是否可以区分这两种类型的初始化? 解决方法 complx two = complx(3,4)
比较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对象,然后使用copy / move构造函数构造两个.

但是,可以省略此复制/移动:

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

但是,复制构造函数仍然必须是可访问的,就像它被调用一样.

这两个初始化可以区分吗?假设复制/移动有效,不可靠,不.如果编译器确实在复制初始化中删除了副本,或者如果副本表现良好并且没有任何额外的副作用,那么两者的行为将完全相同.如果它没有删除副本并且副本有一些额外的副作用,那么你会注意到一个区别.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读