0

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?

Ali250
  • 652
  • 1
  • 5
  • 19
  • You need first to initialize the static variable with no parenthesis or with braces. And then assign to it the object you want to copy in main. Sorry for the answer I didn't see the comments. – 101010 Nov 18 '15 at 22:31
  • 1
    A very similar question: http://stackoverflow.com/questions/33572283/can-i-initialize-a-static-const-member-at-run-time-in-c. – R Sahu Nov 18 '15 at 22:33
  • As I said, I was initially using no parenthesis and got the aforementioned error. Using brace initialization gives the error `must be initialized by constructor, not by {...}` which is preceded by another error `extended initializer lists only available with std=c++11` – Ali250 Nov 18 '15 at 22:35
  • @Ali250 is there a good reason you are not using C++11 ? – M.M Nov 18 '15 at 22:39
  • @M.M Long story short, I'm using a build system called `catkin` which is for the Robot Operating System (ROS). Officially, ROS is still on C++03 and I'm using many libraries written in C++03 and people on their forums usually say that mixing c++03 and c++11 code isn't a good idea. – Ali250 Nov 19 '15 at 13:39

1 Answers1

1

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.

M.M
  • 138,810
  • 21
  • 208
  • 365