[英]C++ Static variable accessible by class member
Please have a look at the following code: 请看下面的代码:
#include<string>
class abc
{
public:
static const abc PENDING;
private:
static const string PENDING_STATUS_CD;
abc ( const string& iStatus )
{
//...........
Logintodatabase();
//.............
logoutfromdatabase();
}
};
const string abc::PENDING_STATUS_CD = "P";
const abc abc::PENDING ( abc::PENDING_STATUS_CD );
Once the const abc abc::PENDING( abc::PENDING_STATUS_CD ); 一旦const abc abc :: PENDING(abc :: PENDING_STATUS_CD); is called, it will call constructor
abc ( const string& iStatus )
. 被调用时,它将调用构造函数
abc ( const string& iStatus )
。
In fact if more than one static class variable is defined inside class, for each initialization it will call the constructor. 实际上,如果在类内部定义了多个静态类变量,则对于每次初始化,它将调用构造函数。
This constructor is responsible for opening & closing the database. 该构造函数负责打开和关闭数据库。
For each static variable initialization, the database will open & close. 对于每个静态变量初始化,数据库将打开和关闭。
Suppose this class is used by more than one process then so many times database will open & close. 假设这个类被多个进程使用,那么数据库将打开和关闭很多次。
can you suggest how to overcome this issue? 你能建议如何克服这个问题吗?
can anyone tell me how to design this logic? 谁能告诉我如何设计这种逻辑?
The database is a dependency. 数据库是一个依赖项。 Pass it from outside, maybe in the constructor.
从外部传递它,也许在构造函数中传递它。 Assume it already is open and let the caller of your class worry about opening, closing or caching connections.
假设它已经打开,让您的类的调用者担心打开,关闭或缓存连接。
On a technical level, if you don't want to do dependency injection, look up connection pooling
for your respective database. 从技术上讲,如果您不想进行依赖项注入,请查找您各自数据库的
connection pooling
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.