我可以显式调用一个复制构造函数吗? [英] Can I call a copy constructor explicitly?

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

问题描述

我有点困惑的复制构造函数的机制。如果我错了,请更正我:



如果方法引用一个对象作为参数,并且类定义了一个副本construtor,那么该类使用构造函数创建一个自己的副本,并传递到函数,而不是对原始对象的引用?



此外,可以调用

  Object * obj = new Object (& anotherObject); 

以创建anotherObject的副本?

解决方案

否,如果函数引用:

  void f1(Object& o); //调用引用

,则不进行复制。如果函数取值:

  void f2(Object o); //通过值调用

然后使用复制构造函数由编译器创建一个副本。 >

是的,当你说:

  Object * obj = new Object anotherObject); // not& anotherObject 

复制构造函数是明确使用的(假设anotherObject类型为Object)。但是,在这种情况下,使用 new 没有什么神奇之处:

  Object obj2(anotherObject); 

也使用复制构造函数。


I'm a little confused as to the mechanics of the copy constructor. Correct me if I'm wrong:

If a method takes a reference to an object as a parameter, and the class defines a copy construtor, then the class uses the constructor to create a copy of itself and that gets passed to the function instead of a reference to the original object?

Furthermore, one can call

Object * obj = new Object(&anotherObject);

to create a copy of anotherObject?

解决方案

No, if a function take a reference:

void f1( Object & o );   // call by reference

then no copy is made. If a function takes a value:

void f2( Object o );   // call by value

then a copy is created by the compiler using the copy constructor.

And yes, when you say:

Object * obj = new Object(anotherObject);   // not &anotherObject

the copy constructor is used explicitly (assuming anotherObject is of type Object.) There is nothing magic about the use of new here, however - in this case:

Object obj2(anotherObject);

the copy constructor is also used.

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

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