Dan*_*ook 16 c++ dry copy-constructor assignment-operator
我有一个类,需要一个非默认的复制构造函数和赋值运算符(它包含指针列表).有没有通用的方法来减少复制构造函数和赋值运算符之间的代码重复?
sel*_*tze 17
编写自定义复制构造函数和赋值运算符并不是"通用方法",它们适用于所有情况.但是有一种叫做"复制 - 交换"的成语:
class myclass
{
...
public:
myclass(myclass const&);
void swap(myclass & with);
myclass& operator=(myclass copy) {
this->swap(copy);
return *this;
}
...
};
Run Code Online (Sandbox Code Playgroud)
它在许多(但不是全部)情况下都很有用.有时你可以做得更好.向量或字符串可以有更好的赋值,如果它足够大,它会重用分配的存储.
Vij*_*hew 16
将公共代码分解为私有成员函数.一个简单(相当人为)的例子:
#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;
}
Run Code Online (Sandbox Code Playgroud)
My &My::operator = (My temp) // thanks, sellibitze
{
swap (*this, temp);
return *this;
}
Run Code Online (Sandbox Code Playgroud)
并实施专业化std::swap<> (My &, My &).
| 归档时间: |
|
| 查看次数: |
4947 次 |
| 最近记录: |