如果自己设计的一个类,不想支持复制操作,一般需要将copy constructor和copy assignment声明为private.
例子:
#include <cstdlib> #include <iostream> using namespace std; class A { public: A(int x = 0): x_(x) { } int X() const { return x_; } private: A(A const&); A& operator=(A const&); private: int x_; }; /* * */ int main(int argc, char** argv) { A a(6); cout << a.X() << endl; A a2(a); A a3; a3 = a; return 0; }编译器报错:
main.cpp:23:5: error: ‘A::A(const A&)’ is private main.cpp:37:11: error: within this context main.cpp:24:8: error: ‘A& A::operator=(const A&)’ is private main.cpp:40:10: error: within this context
不过避免重复写这些代码是程序员的惯性。
看看boost提供的noncopyable类。现在很多C++产品都在用。改一下代码,这样使用:
#include <cstdlib> #include <iostream> using namespace std; #include <boost/utility.hpp> using namespace boost; class A : noncopyable { public: A(int x = 0): x_(x) { } int X() const { return x_; } private: int x_; }; /* * */ int main(int argc, char** argv) { A a(6); cout << a.X() << endl; A a2(a); A a3; a3 = a; return 0; }编译器也报错,就是看起来累点:
/usr/include/boost/noncopyable.hpp: In copy constructor ‘A::A(const A&)’: /usr/include/boost/noncopyable.hpp:27:7: error: ‘boost::noncopyable_::noncopyable::noncopyable(const boost::noncopyable_::noncopyable&)’ is private main.cpp:15:7: error: within this context main.cpp: In function ‘int main(int, char**)’: main.cpp:36:11: note: synthesized method ‘A::A(const A&)’ first required here /usr/include/boost/noncopyable.hpp: In member function ‘A& A::operator=(const A&)’: /usr/include/boost/noncopyable.hpp:28:26: error: ‘const boost::noncopyable_::noncopyable& boost::noncopyable_::noncopyable::operator=(const boost::noncopyable_::noncopyable&)’ is private main.cpp:15:7: error: within this context main.cpp: In function ‘int main(int, char**)’: main.cpp:39:10: note: synthesized method ‘A& A::operator=(const A&)’ first required here make[2]: *** [build/Debug/GNU-Linux-x86/main.o] Error 1
namespace noncopyable_ // protection from unintended ADL { class noncopyable { protected: noncopyable() {} ~noncopyable() {} private: // emphasize the following members are private noncopyable( const noncopyable& ); const noncopyable& operator=( const noncopyable& ); }; } typedef noncopyable_::noncopyable noncopyable; }
然后声明了copy constructor和copy assignment为private.
非常简单实用。文档中说道总有些包含资源(比如文件和网络通信连接)的对象你不想被拷贝,那就用它吧。