Why should the copy constructor accept its parameter by reference in C++?

前端 未结 8 1308
离开以前
离开以前 2020-11-22 17:00

Why must a copy constructor\'s parameter be passed by reference?

相关标签:
8条回答
  • 2020-11-22 17:45

    The alternative to pass-by-reference is pass-by-value. Pass-by-value is really pass-by-copy. The copy constructor is needed to make a copy.

    If you had to make a copy just to call the copy constructor, it would be a conundrum.

    (I think the infinite recursion would occur in the compiler and you'd never actually get such a program.)

    Besides rational reasons, it's forbidden by the standard in §12.8/3:

    A declaration of a constructor for a class X is ill-formed if its first parameter is of type (optionally cv- qualified) X and either there are no other parameters or else all other parameters have default arguments.

    0 讨论(0)
  • 2020-11-22 17:46

    It is necessary to pass object as reference and not by value because if you pass it by value its copy is constructed using the copy constructor.This means the copy constructor would call itself to make copy.This process will go on until the compiler runs out of memory.

    0 讨论(0)
提交回复
热议问题