search

Home  >  Q&A  >  body text

为什么c++拷贝构造函数一定是传引用?为什么不能是传指针的方式?

值传递会造成死循环。但传指针为什么不行?指针不是是传地址吗,为什么不能用指针?有个博客说传指针也是传值,请问究竟是为什么

ringa_leeringa_lee2767 days ago894

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-17 13:47:32

    No other reason, because if passed by pointer, the writing method would be too ugly.
    Pointer value transfer is compared to the transfer of actual parameters and formal parameters, and the value of the address is transferred.

    #include <iostream>
    using namespace std;
    
    class MyClass {
    public:
        MyClass() {
            cout << "constructor called"<<endl;
        }
    
        MyClass(const MyClass &v) {
            cout << "copy constructor called" << endl;
        }
    };
    
    int main() {
        MyClass A;
        MyClass B = A; //这里调用的是拷贝构造函数,写法目前看起来是自然的,用指针写的话,怎么表达这个写法?
        return 0;
    }

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:47:32

    Passing a pointer does not cause an infinite loop problem, but you have to implement the compiler yourself so that it knows when a copy operation occurs to call the function you wrote to pass the pointer.
    The pointer itself is a variable, but its value is the address of another variable, so passing a pointer is also passing by value.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 13:47:32

    It is recommended to refer to the difference between deep copy and shallow copy

    reply
    0
  • Cancelreply