我是C++新手,我不懂C++拷贝分配和复制构造函数中的一些语法:
复制构造函数:
vector::vector(const vector& arg)
// allocate elements, then initialize them by copying
:sz{arg.sz}, elem{new double[arg.sz]}
{
copy(arg,arg+sz,elem); // std::copy(); see §B.5.2
}副本评估:
class vector {
int sz;
double* elem;
public:
vector& operator=(const vector&); // copy assignment
//...
};
vector& vector::operator=(const vector& a)
// make this vector a copy of a
{
double* p = new double[a.sz]; // allocate new space
copy(a.elem,a.elem+a.sz,elem); // copy elements
delete[] elem; // deallocate old space
elem = p; // now we can reset elem
sz = a.sz;
return *this; // return a self-reference (see §17.10)
}我不明白的是:
为什么在复制构造函数中我们复制这样的元素:
copy(arg,arg + sz,elem),但是在像这样的拷贝分析中:copy(a.elem,a.elem + a.sz,elem)
你能解释一下这个区别吗?
发布于 2018-01-04 17:13:54
区别在于参数的名称和传递给std:: copy的类型。
std:: copy是一个模板函数;因此它改变了参数的类型(double,int,string,.)
您需要担心的是参数描述(来自http://en.cppreference.com/w/cpp/algorithm/copy)。
template< class InputIt, class OutputIt >
OutputIt copy( InputIt first, InputIt last, OutputIt d_first );https://stackoverflow.com/questions/48100041
复制相似问题