问题描述
大家好,
我想知道为什么复制构造函数总是将引用作为参数。为什么不能指针。
我知道使用引用的好处是避免应用程序崩溃。如果你传递对象作为任何函数的引用,那么编译时检查就完成了检查对象的创建/存在。
但是如果你错误地将未初始化的/ 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
推荐答案
我想知道为什么复制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.
这篇关于将指针参数传递给复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!