对于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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值