From: stackoverflow
#include <iostream>
struct InkPen
{
void Write()
{
this->WriteImplementation();
}
void WriteImplementation()
{
std::cout << "Writing using a inkpen" << std::endl;
}
};
struct BoldPen
{
void Write()
{
std::cout << "Writing using a boldpen" << std::endl;
}
};
template<class PenType>
class Writer : public PenType
{
public:
void StartWriting()
{
PenType::Write();
}
};
/* 更好的! */
template<class PenType>
class Writer2
{
public:
Writer2(const PenType& pen = PenType()) : pen(pen) {}
void StartWriting()
{
pen.Write();
}
private:
PenType pen;
};
int main()
{
Writer<InkPen> writer;
writer.StartWriting();
Writer<BoldPen> writer1;
writer1.StartWriting();
InkPen pen;
// wrong
//Writer<pen> writer3;
//writer3.StartWriting();
Writer2<InkPen> writer22(pen); //ok
Writer2<InkPen> writer23; //ok
// Writer2 writer24(pen); // error
writer22.StartWriting();
return 0;
}
Noncopyable resources
Some resources cannot or should not be copied, such as file handles or mutexes. In that case, simply declare the copy constructor and copy assignment operator as private without
giving a definition:
private:
person(const person& that);
person& operator=(const person& that);
Alternatively, you can inherit from boost::noncopyable or
declare them as deleted (C++0x):
person(const person& that) = delete;
person& operator=(const person& that) = delete;
本文探讨了C++中如何处理不可复制或不应复制的资源,如文件句柄和互斥锁。通过声明不可复制的构造函数和赋值操作符,或者继承自`noncopyable`类,来实现非复制行为。
1439

被折叠的 条评论
为什么被折叠?



