Inv*_*tus 2 c++ singleton copy-constructor
我应该如何为我的单例类编写一个复制构造函数,以防止创建一个新对象,因为我已经有了一个.什么是overload = operator的最佳实践
#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() <<"\n";
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() <<"\n";
delete a;
delete b;
getch();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何编写复制构造函数代码并重载相等的运算符以防止创建更多对象?
Joh*_*erg 10
要么使其不可复制,如此处所述
或者您定义复制构造函数和赋值运算符,以便获得相同的单例.取决于您实际需要的功能.
通常也应该禁止分配(如上面的链接):
class Rect{
Rect( const Rect& ) = delete;
Rect& operator=( const Rect& ) = delete;
. . .
}
Run Code Online (Sandbox Code Playgroud)
这也禁止移动操作.
你可能也想知道这一点: 单身人士真的那么糟糕吗?
单身人士很荒谬,只需使用免费功能.
仍然,回答你的问题......
C++ 11:
class Foo {
public:
Foo (const Foo &) = delete;
Foo & operator = (const Foo &) = delete;
};
Run Code Online (Sandbox Code Playgroud)
C++ 03;
class Foo {
private:
// Don't write bodies.
Foo (const Foo &);
Foo & operator = (const Foo &);
};
Run Code Online (Sandbox Code Playgroud)