Ali250
Ali250

Reputation: 662

Initializing static class object with no zero argument constructor c++

The relevant part of my code is as follows:

In foo.h:

namespace foo_ns {
class Foo
{
    static Class1 object1;
};
}

In foo.cpp

#include <foo.h>
namespace foo_ns {

Class1 Foo::object1(/*another object. Need to call copy constructor*/)

}

Here, "another object" is defined in main(). Furthermore, Class1 is part of a large library and has no zero argument constructors, so simply removing the parenthesis gives a no matching function call error during compilation. From what I understand, static initialization MUST be performed outside of any function.

So ithere any workaround for this?

Upvotes: 0

Views: 340

Answers (1)

M.M
M.M

Reputation: 141638

Of course, if Class1 has methods that you can use later then an easy solution would be:

Class1 Foo::object1(some_rubbish);

// in main
object1 = Class1(the_real_initializer);

If Class1 does not have a working assignment operator, but it can safely be destroyed and re-created, you can write in main:

object1.~Class1();
new(&object1) Class1(the_real_initializer);

although if this constructor throws then you have to abort the program.


If it is not possible to destroy a Class1 correctly before the end of the program then you will have to defer its initialization, e.g.:

static std::unique_ptr<Class1> p_object1;

and then in main, when you are ready,

p_object1.reset( new Class1(bla bla bla) );

This way you will have to change any other code that accesses object1. to use p_object1-> instead.

Upvotes: 1

Related Questions