拷贝构造函数第一个参数最好使用const
拷贝构造函数的第一个参数要求是自身类型的引用,但是没有一定要求具有底层const属性即对常量的引用,但是使用时最好加上const,原因是我们可能在某些“不知道”的情况下对常量对象调用拷贝构造函数。
来看一个例子
class HasPtr{
public:
HasPtr(const std::string &s=std::string()):ps(new std::string(s)),i(0){
std::cout<<"construction call"<<std::endl;
}
HasPtr(HasPtr &hasptr):i(hasptr.i),ps(new std::string(*hasptr.ps))
{
std::cout<<"copy construction call"<<std::endl;;
}
~HasPtr()
{ delete ps;
std::cout<<"deconstruction call"<<std::endl; }
private:
std::string *ps;
int i;
};
int main()
{
HasPtr ptr1("a"),ptr2("c"),ptr3("b");
std::vector<HasPtr> vec{ptr1,ptr2,ptr3};
return 0;
}


