Is it necessary to have static constructors when w

2019-07-20 21:03发布

问题:

If I were to follow the RAII rule and would be developing a class in C++, would it be necessary to have static constructors? Will static constructors help me in any way or would be a wrong step to do?

回答1:

I take it you are talking about a static factory function that creates an instance of your class (As others pointed out). In which case, you don't need to use the RAII pattern.

Remember you need your class to be stack allocated, so that the constructor is called (automatically) and initializes various data. also, the destructor is called (automatically) when the stack unwinds and performs other operations: such as freeing resources etc..

If your class initializes it's data statically then the RAII pattern will fail, since statically held data is not bound to an instance of a class. So when the stack unwinds there is no instance to destruct, no destructor gets called, and the RAII pattern is not implemented.



回答2:

That doesn't make any sense, you cannot have a static constructor. The entire purpose of the constructor is to initialize a specific instance of a class; if it were static, it wouldn't belong to any instance.

RAII just says that you need to free a resource in the destructor, and that the acquisition of that resource happens with the initialization (construction) of the object who will run that destructor. (Which entails you need a working or forbidden copy-constructor, along with a working assignment operator.)



回答3:

You could have some static function CreateInstance() that would return you the instance of your class.

With RAII your function will probably have to return you some smart pointer to the instance you created to avoid copying of the actual object. Then you store this pointer, copy it if you need it in other places. When all smart pointers are destructed the object will be destructed too. If that's what you want, then yes - you could have "static constructor".

Of course it's not a must in RAII and normally would be just unneeded complication.



标签: c++ raii