C ++: assign value to a variable of a global class

Consider a class MyClass

that has a default no constructor .

I want to write some code that looks like this:

MyClass instance;

void init_system() {
    instance = MyClass(parameters, of, the, constructor);
}

      

The code I wrote above is certainly not buggy MyClass doesn't have a C'tor that takes no arguments.

Is there any correct way to do this, or should I implement a workaround eg. using shared pointers?

+3


source to share


3 answers


Well, either your class's default object can reasonably exist, or it can't.
In the latter case, you might be interested std::optional

( boost::optional

before C ++ 17) to defer object construction.



+7


source


You can transfer object initialization to your function init_system()

:

MyClass& init_system()
{
   static MyClass instance(parameters, of, the, constructor);
   return instance;
}

      



You might also want to take a look at the singleton pattern and read the extensive discussions about it;)

And yes, another solution might be to use unique_ptr<>

or shared_ptr<>

.

+1


source


There are two ways to achieve this ...

MyClass instance(parameters, of, the, constructor);

      

Initializes MyClass with the correct parameters.

Singleton Pattern

MyClass & MyClass::getInstance(){
   static MyClass instance( parameters, of, constructor );
   return instance;
}

      

with getInstance returned during the call.

The second pattern improves control when the object is built.

+1


source







All Articles