这个很早就搞明白了,只是这里系统整理一下。
例1:
#include<iostream>
using namespace std;
class Test {
public:Test(int test_data = 0) :test_data(test_data){cout << "ctor" << endl;}Test(const Test&obj) { cout << "copy ctor" << endl; }Test& operator=(const Test&other) {cout << "copy assignment" << endl;if (this == &other){return *this;}this->test_data = other.test_data;return *this;}
private:int test_data;
};
int main()
{Test t1;Test t2(t1);//copy ctorcout << "-------------" << endl;Test t3 = t1;//copy ctorcout << "-------------" << endl;t3 = t2; //copy assignmentsystem("pause");return 0;
}
其实很简单,copy ctor是针对一个未存在的对象进行初始化;copy assignment是针对已存在的对象进行初始化。
例2:
#include<iostream>
#include<functional>
#include<numeric>
using namespace std;// TEMPLATE STRUCT plus
template<class _Ty = void>
struct my_plus
{ // functor for operator+typedef _Ty first_argument_type;typedef _Ty second_argument_type;typedef _Ty result_type;my_plus() { cout << "my_plus ctor" << endl; }my_plus(my_plus&obj) { cout << "my_plus copy ctor" << endl; }constexpr _Ty operator()(const _Ty& _Left, const _Ty& _Right) const{ // apply operator+ to operandsreturn (_Left + _Right);}
};template<class _InIt,class _Ty,class _Fn2> inline_Ty my_accumulate(_InIt _First, _InIt _Last, _Ty _Val, _Fn2 _Func)
{ // return sum of _Val and all in [_First, _Last), using _Funcfor (; _First != _Last; ++_First)_Val = _Func(_Val, *_First);return (_Val);
}// FUNCTION TEMPLATE accumulate
template<class _InIt,class _Ty> inline_Ty my_accumulate(_InIt _First, _InIt _Last, _Ty _Val)
{ // return sum of _Val and all in [_First, _Last)return (my_accumulate(_First, _Last, _Val, my_plus<_Ty>()));
}
int main() {//二元函数对象的使用int a[] = { 1,2,3,4,5 };const int N = sizeof(a) / sizeof(int);cout << my_accumulate(a, a + N, 0, my_plus<int>()) << endl;//15cout << "-------------------" << endl;my_plus<int> obj;cout << my_accumulate(a, a + N, 0, obj) << endl;//15system("pause");return 0;
}
这里其实想说的就是函数形参为类的对象,临时对象作为实参传入时的情况,编译器会进行优化,只调用了一次ctor:
#include<iostream>
using namespace std;
class Test {
public:Test(int test_data = 0) :test_data(test_data){cout << "ctor" << endl;}Test(const Test&obj) { cout << "copy ctor" << endl; }Test& operator=(const Test&other) {cout << "copy assignment" << endl;if (this == &other){return *this;}this->test_data = other.test_data;return *this;}
private:int test_data;
};void fun(Test t) {}int main()
{Test t1;fun(t1);cout << "------" << endl;fun(Test());system("pause");return 0;
}
例3:
稍作改动,将函数的返回类型也改成类的对象:
#include<iostream>
using namespace std;
class Test {
public:Test(int test_data = 0) :test_data(test_data){cout << "ctor" << endl;}Test(const Test&obj) { cout << "copy ctor" << endl; }Test& operator=(const Test&other) {cout << "copy assignment" << endl;if (this == &other){return *this;}this->test_data = other.test_data;return *this;}
private:int test_data;
};Test fun(Test t) { return t; }int main()
{Test t1;fun(t1);cout << "------" << endl;fun(Test());system("pause");return 0;
}
显然,当fun执行完毕,返回的时候还会额外增加一次copy ctor的调用。