我有一个类,需要一个非默认的复制构造函数和赋值运算符(它包含指针列表)。有没有一种通用的方法可以减少复制构造函数和赋值运算符之间的代码重复?
我有一个类,需要一个非默认的复制构造函数和赋值运算符(它包含指针列表)。有没有一种通用的方法可以减少复制构造函数和赋值运算符之间的代码重复?
没有一种"通用的方法"可以编写适用于所有情况的自定义复制构造函数和赋值运算符。但有一种习惯用法称为"拷贝并交换(copy-&-swap)":
class myclass
{
...
public:
myclass(myclass const&);
void swap(myclass & with);
myclass& operator=(myclass copy) {
this->swap(copy);
return *this;
}
...
};
在许多情况下这很有用(但并非所有情况)。有时您可以做得更好。如果向量或字符串足够大,它们可能具有更好的赋值方式,可以重用已分配的存储空间。
this->swap(copy)
有什么特别之处,还是 swap(copy)
也可以工作? - kevinarpeswap(copy)
也可以。有时我会写this->
来更明确地表示它是数据成员或成员函数。 - sellibitze将常见代码提取到一个私有成员函数中。以下是一个简单(有点勉强)的示例:
#include <iostream>
class Test
{
public:
Test(const char* n)
{
name = new char[20];
strcpy(name, n);
}
~Test()
{
delete[] name;
}
// Copy constructor
Test(const Test& t)
{
std::cout << "In copy constructor.\n";
MakeDeepCopy(t);
}
// Assignment operator
const Test& operator=(const Test& t)
{
std::cout << "In assignment operator.\n";
MakeDeepCopy(t);
}
const char* get_name() const { return name; }
private:
// Common function where the actual copying happens.
void MakeDeepCopy(const Test& t)
{
strcpy(name, t.name);
}
private:
char* name;
};
int
main()
{
Test t("vijay");
Test t2(t); // Calls copy constructor.
Test t3("");
t3 = t2; // Calls the assignment operator.
std::cout << t.get_name() << ", " << t2.get_name() << ", " << t3.get_name() << '\n';
return 0;
}
t2 = t2
赋值运算符是无法正常工作的。(如果你想对它们排序,这一点很重要。) - dave4420My &My::operator = (My temp) // thanks, sellibitze
{
swap (*this, temp);
return *this;
}
并实现一个专门的std::swap<> (My &, My &)
。