将指针参数传递给复制构造函数 [英] Passing pointer argument to copy constructor

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

问题描述

大家好,



我想知道为什么复制构造函数总是将引用作为参数。为什么不能指针。



我知道使用引用的好处是避免应用程序崩溃。如果你传递对象作为任何函数的引用,那么编译时检查就完成了检查对象的创建/存在。

但是如果你错误地将未初始化的/ NULL指针传递给函数那么那个检查就没有完成在编译时,这会导致应用程序崩溃。



但程序员可以保证初始化ptr并传递给

复制构造函数。



有人可以告诉我选择参考资料的确切原因。


提前致谢

Hi All,

I would like to know why copy constructor always takes reference as a parameter. Why can''t it take pointer.

i know that benefit of using reference is to avoid application crash. If you pass object as a reference to any function then compile time checking is done to check object is created/exist.
But if you pass uninitialized/NULL pointer to functions by mistake then that checking is not done at compile time and that is results in to application crash.

but that is something programmer can guarantee to initialize ptr and pass to
copy constructor.

Can anybody tell me what could be the exact reason for choosing references only.

Thanks in advance

推荐答案



这可能会让你有所了解:

here [ ^ ]

以及这里 [ ^ ]


引用:

我想知道为什么复制const ructor始终将引用作为参数。为什么不能指针。

I would like to know why copy constructor always takes reference as a parameter. Why can''t it take pointer.



因为它有意义(它比传递指针更有意义):你用更整洁的语法获得相同的效果。

注意可能创建接受指向对象的指针的构造函数。


Because it makes sense (it makes more sense than passing a pointer): you obtain the same effect with a neater syntax.
Note you may create a constructor accepting a pointer to the object.


由于复制构造函数是由编译器在未由用户指定时生成的,对于用于编译器定义的复制构造函数的用户定义的复制构造函数使用相同的签名是有意义的。



如果某人定义了一个带指针的构造函数而不是引用,那么如果调用者忘记获取要从中创建新对象的对象的地址,那么编译器生成的复制构造函数(如引用)将不是使用带有指针的用户构造函数。使用。



使用引用来保持一致性也是有意义的。例如,所有运算符如=,==,< =,+ =通常都会使用引用来定义。
Since the copy constructor is generated by the compiler when not specified by the user, it make sense to use the same signature for user-defined copy constructor that is used for compiler-defined copy constructor.

If someone define a constructor that take a pointer instead of a reference, then if the caller forget to take the address of the object from which the new object is to be created, then instead of using user-constructor with a pointer, the compiler generated copy constructor (wioth a reference) would be used.

It also make sense to use a reference for consistency. For exemple, all operators like =, ==, <=, += would normally be defined using references.


这篇关于将指针参数传递给复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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