Having a simple class:
class A {
public:
A() {}
void set(int value) { value_ = value; }
private:
int value_;
};
and its global instance:
A a;
-
Is it OK to call method
seton a not yet constructed objecta? That can happen when for examplea.set(123)is called from a constructor of another global object in another translation unit. -
Will the value in the object
aset by callinga.set(123)remain when the non-parametric and empty constructor ofAis later called for objecta?
No. You may not call member functions for an object that has not yet begun construction.
(Since the answer is no, your second question requires no answer.)
If you may need to access this global instance from multiple translation units during dynamic initialization, you can use the Meyers singleton technique:
awill be initialized whenglobal_a()is first called. Note that in a multithreaded program you may need to concern yourself with synchronization of the initialization.