为什么c++拷贝构造函数一定是传引用?为什么不能是传指针的方式?
ringa_lee
ringa_lee 2017-04-17 13:45:32
0
3
899

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

ringa_lee
ringa_lee

ringa_lee

reply all(3)
黄舟

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;
}
伊谢尔伦

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.

小葫芦

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template