c++ - copy constructor and the initializer constructor in container and Array

we know you can define constructor and the copy constructor for a user defined class, and if you faile to provide one, the compiler will be able to generate one for you.  The generated ones are called default constructor or default copy constructor, the former will call the default constructor for its member and its base classes, and the later will call the default memberwise copy constructor for its member if the member failes to provide one or the copy constructor if it has provided one, and its applies the same as regard to the base classes object parts.

 

but how it works if we are create a array of user define classes or a container like vector of user defined classes?

 

let's see an example.

 

#include "stdafx.h"

#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

using std::string;
using std::cout;
using std::endl;
using std::vector;
using std::copy;
using std::inserter;


class CustomClass 
{
public: 
	CustomClass(string name_, int age_) : name(name_), age(age_) {
	  cout << "inside CustomClass(string name, int age)" << endl;
	}
	CustomClass(const CustomClass& rhs) : name(rhs.name), age(rhs.age) {
	  cout << "inside CustomClass(const CustomClass& rhs)" << endl;
	}
private:
	std::string name;
	int age;
};

void TestVectorCopy()
{
	//vector<CustomClass> customClasses(4) = 
	// the results shows that it will first call the constructor with (string, int), then with the const CustomClass& - the copy constructor
	CustomClass customClasses[] = { CustomClass("joe", 29), CustomClass("Yun", 30), CustomClass("Cliff", 31), CustomClass("Nora", 31), CustomClass("Tom", 30) }; 

	vector<CustomClass> v_customClasses;

	v_customClasses.reserve(sizeof(customClasses) / sizeof(CustomClass));

	// as you can see, there are in total const CustomClasses&  called when copy from the CustomClass[] to the vector<CustomClass>
	copy(customClasses, customClasses + 4, inserter(v_customClasses, v_customClasses.begin())); 

	// as you will find in the following code, another CustomClasses is called
	vector<CustomClass> v_customClasses2 = v_customClasses;

	vector<CustomClass> v_customClasses3;
	v_customClasses.reserve(v_customClasses2.size());
	copy(v_customClasses.cbegin(), v_customClasses.cend(), inserter(v_customClasses3, v_customClasses3.begin()));

}

 

the result shows that copy constructor is called for each element of container, and the constructor is called for each of the initializer value of the first array.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值