这是一个复制构造函数吗? [英] Is this a copy constructor?

查看:137
本文介绍了这是一个复制构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A {};
class B { public: B (A a) {} };

A a;
B b=a;

从技术上讲,这是一个复制构造函数,应用于创建 b

Technically speaking, is a copy constructor being applied here on the creation of b ?

推荐答案


从技术上讲,关于b的创建?

Technically speaking, is a copy constructor being applied here on the creation of b ?

是...但可能不是你的想法。 在创建b时调用的复制构造函数,以便执行参数传递值 A a 作为B构造函数的参数。

Yes...but probably not how you think. A's copy constructor is being invoked on the creation of b, in order to do the pass-by-value of the parameter A a as a parameter to the B constructor.

然而,它不是在创建时运行B的复制构造函数b。

However, it is not running B's copy constructor in the creation of b.

EDIT:每天都会学到新的东西。显然,甚至更技术上来说,如@CharlesBailey指出的...如果你使用 B b = a; 语法(复制初始化)而不是 B b(a); 语法(直接初始化),需要创建类型B 的临时值 。在这一点上,B的拷贝构造函数将被调用。

One learns something new every day. Apparently even more-technically-speaking, as @CharlesBailey pointed out...if you use the B b = a; syntax ("copy initialization") instead of B b (a); syntax ("direct initialization"), a temporary value of type B might need to be created. At this point B's copy constructor would wind up being called.

这是一个很难研究的现象,但Charles指出,gcc有一个 -fno-elide-constructors 选项(也:复制Elision上的维基百科) )@ JesseGood的链接有一个详尽的解释和一些演示代码:

It's a little hard to study the phenomenon, but Charles points out that gcc has a -fno-elide-constructors option (also: Wikipedia on Copy Elision) @JesseGood's link has an exhaustive explanation and some demonstration code:

C ++在复制初始化和直接初始化之间有区别吗?

Is there a difference in C++ between copy initialization and direct initialization?

这篇关于这是一个复制构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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