对于C++拷贝构造函数的思考

Posted smstong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对于C++拷贝构造函数的思考相关的知识,希望对你有一定的参考价值。

//
// When a variable contains an object directly,
// copying, assignment and returning becomes complex.
// In C++, "copy constructor" and "assignment operator" are
// necessary for those operations.
//
// In practice, coping objects is rarely needed. So, other OO
// languges usually don't operate on objects directly, but on
// their references(pointers) instead.
//
// For example, in Java/Python, a variable contains a reference(pointer) to
// the actual object. As a result, copying, assignment, and
// returning such a variable are just simple as if it was an
// integer.
//
// In C++, we can use class pointers to mimic references in Java,
// but code full of "*" looks ugly.
//
//

#include <iostream>
using namespace std;
class A

        public:
                // constructor
                A()
                
                        cout << "A::A() being called\\n";
                
                // copy constructor
                A(const A& old_obj)
                
                        cout << "A::A(const A&) being called.\\n";
                
;
// A's copy constructor will be called
void f1(const A obj)

        return;

// A's copy constructor will not be called
void f2(const A& obj)

        return;

A f3(const A& obj)

        // A's copy constructor will be called
        return obj;

// copy constructor will NOT be called
A& f4(A& obj)

        return obj;


int main(int argc, char** argv)

        A o1;
        A o2 = o1; // call copy constructor
        A o3;
        o3 = o1;  // assignment operator
        cout << "f1\\n";
        f1(o1);
        cout << "f2\\n";
        f2(o1);
        cout << "f3\\n";
        f3(o1);
        cout << "f4\\n";
        f4(o1);

RESULT:

$ ./a.out
A::A() being called
A::A(const A&) being called.
A::A() being called
f1
A::A(const A&) being called.
f2
f3
A::A(const A&) being called.
f4

以上是关于对于C++拷贝构造函数的思考的主要内容,如果未能解决你的问题,请参考以下文章

对于C++拷贝构造函数的思考

C++深拷贝和浅拷贝细节理解

深度分析C++默认构造函数拷贝构造函数

C++ 拷贝构造与拷贝赋值

C++ 拷贝构造与拷贝赋值

C++拷贝构造函数详解