How should I write a copy constructor in case of Singleton class and how should I overload = operator for same?
我应该如何为我的singleton类编写一个复制构造函数来防止创建一个新对象,因为我已经有了一个新对象。过载的最佳实践是什么=相同的运算符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | #include <iostream> #include <stdio.h> #include <conio.h> using namespace std; class Rect { int length; int breadth; static int count; static int maxcount; Rect() {}; Rect(const Rect& abc){}; public : ~Rect(); int area_rect() {return length*breadth;} void set_value(int a,int b); static Rect* instance() { Rect* ptr=NULL; if(count < maxcount) { ptr=new Rect ; count++; } return ptr; } }; int Rect::count = 0; int Rect::maxcount = 1; void Rect::set_value(int a,int b) { length=a; breadth=b; } Rect::~Rect() { count --; } int main() { Rect* a= Rect::instance(); //creates first object // Rect* c= Rect::instance(); //fails to create second object //as maxcount=1 and returns NULL a->set_value(10,3); cout <<"area realted to object a :" << a->area_rect() <<" "; Rect* b=a;//allows creation of second object which I dont want b->set_value(10,4); cout <<"area realted to object b :" << b->area_rect() <<" "; delete a; delete b; getch(); return 0; } |
如何编写复制构造函数代码和重载等号运算符来防止进一步对象的创建?
要么你让它不可复制,如这里所解释的。
如何使C++对象不可复制?
或者定义复制构造函数和赋值运算符,以便获得相同的单例。取决于您实际需要的功能。
通常也应该禁止分配(如上面的链接所示):
1 2 3 4 5 | class Rect{ Rect( const Rect& ) = delete; Rect& operator=( const Rect& ) = delete; . . . } |
这也禁止移动操作。
您可能还想知道:单身汉真的那么坏吗?
单件是荒谬的,只是使用免费的功能。
不过,要回答你的问题…
C++ 11:
1 2 3 4 5 | class Foo { public: Foo (const Foo &) = delete; Foo & operator = (const Foo &) = delete; }; |
C++ 03;
1 2 3 4 5 6 | class Foo { private: // Don't write bodies. Foo (const Foo &); Foo & operator = (const Foo &); }; |
这里有一个相关的答案:如果您不希望有人创建一个对象,就不要给他们公共构造函数!
说真的,您可以拥有一个工厂对象,使它成为您想要限制其构造的类的朋友,并使该类的构造函数成为私有的。通过这种方式访问对象(此时甚至不必创建对象)的唯一方法是通过工厂。
例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #include <boost/noncopyable.hpp> #include <string> class ConnectionFactory; class DatabaseConnection : boost::noncopyable { // can only be created by ConnectionFactory which happens to // know how to connect to our database server! friend class ConnectionFactory; DatabaseConnection(std::string username, std::string password /*etc*/); // don't want any random user to reset the connection! ~DatabaseConnection(); public: // public interface bits void Execute(const Select&); // ... }; ConnectionFactory { public: DatabaseConnection& conn(); }; class MayNeedDbConnection { ConnectionFactory factory; public: explicit MayNeedDbConnection(const ConnectionFactory& f) : factory(f) {} void SelectStuff() { DatabaseConnection& conn = factory.conn(); conn.Execute(....); } }; int main() { ConnectionFactory factory; MayNeedDbConnection md(factory); md.SelectStuff(); } |