如果是 Singleton 类,我应该如何编写复制构造函数,以及如何重载 = 运算符?

发布于 2024-12-27 12:52:03 字数 1408 浏览 0 评论 0原文

我应该如何为我的单例类编写一个复制构造函数,以防止创建新对象,因为我已经有了一个。重载=运算符的最佳实践是什么

 #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;
}       

如何编写复制构造函数代码并重载等于运算符以防止创建更多对象?

How should I write a copy constructor for my singleton class to prevent the creation of a new object as I already have one . And what is the best practice to overload = operator for same

 #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;
}       

How to write copy constructor code and overloading equal operator for prevention of creation of further object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

屋檐 2025-01-03 12:52:03

要么按照此处的说明将其设置为不可复制

我该如何制作这个 C++ 对象不可复制?

或者您定义复制构造函数和赋值运算符,以便获得相同的单例。根据您实际想要的功能。

通常也应该禁止分配(如上面的链接所示):

class Rect{
     Rect( const Rect& ) = delete;
     Rect& operator=( const Rect& ) = delete;
     . . .
}

这也禁止移动操作。

您可能还想了解这一点:
单例真的那么糟糕吗?

Either you make it non-copyable as explained here

How do I make this C++ object non-copyable?

or you define the copy constructor and assignment operators such that you get the same singleton. Depending on the functionality you actually want.

Assignment should typically also be forbidden (as on the link above):

class Rect{
     Rect( const Rect& ) = delete;
     Rect& operator=( const Rect& ) = delete;
     . . .
}

This also forbids move operations.

You may also want to know this:
Are Singletons really that bad?

自演自醉 2025-01-03 12:52:03

单例是荒谬的,只使用免费函数。

不过,回答你的问题......

C++11:

class Foo {
public:
    Foo (const Foo &) = delete;
    Foo & operator = (const Foo &) = delete;
};

C++03;

class Foo {
private:
    // Don't write bodies.
    Foo (const Foo &);
    Foo & operator = (const Foo &);
};

Singletons are ridiculous, just use free functions.

Still, to answer your question...

C++11:

class Foo {
public:
    Foo (const Foo &) = delete;
    Foo & operator = (const Foo &) = delete;
};

C++03;

class Foo {
private:
    // Don't write bodies.
    Foo (const Foo &);
    Foo & operator = (const Foo &);
};
苏辞 2025-01-03 12:52:03

这是相关的答案:如果您不希望某人创建对象,请不要给他们公共构造函数!

认真地说,您可以拥有一个工厂对象,使其成为您想要限制其构造的类的朋友,并将该类的构造函数设为私有。这样,访问对象(甚至不必在此时创建它)的唯一方法就是通过工厂。

例如

#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();
}

Here is related answer : if you don't want someone to create an object, don't give them public constructor!

Seriously, you can have a factory object, make it a friend to class which you want to restrict construction of, and make constructor of that class private. This way the only way to access an object (without even necessarily creating it at this time) would be through your factory.

e.g.

#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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文