I have a singleton class defined in file x.h
class x
{
public:
static x* x_instance;
static x* create_x_instance
{
if(!x_instance)
x_instance = new x;
return x_instance;
}
void someMemberFunction()
private:
x() { //some code}
};
extern x *x_interface;
In x.cpp I have the following:
x *x::x_instance = 0;
x *x_interface = x::create_x_instance();
In y.cpp, in the constructor of a another singleton class, I have
x_interface->someMemberFunction();
I get a seg fault because y gets initialized before x. What is the correct way to solve this? I have read many articles on this, but I am still confused.
Just to be clear, using a static member of a static function avoids initialization order problems:
class x
{
public:
static x* get_instance()
{
static x* theInst = new x;
return theInst;
}
void someMemberFunction();
private:
x() { //some code}
};
Later code gets x like this:
x* handle = x::get_instance();
The above is minimal, it should be further improved to manage x lifetime. It might be better to just have theImpl be a static x rather than pointer-to-x, and get_instance() return a reference instead of a pointer.
allow the compiler to generate the singleton on first use by initialising it as a static member of a static function.
Additionally, you can go further and give your singleton object value semantics with zero cost while offering may benefits:
class x
{
struct impl
{
void someMemberFunction() {
}
};
static impl& get_impl() {
static impl _{};
return _;
}
public:
void someMemberFunction()
{
return get_impl().someMemberFunction();
}
};
int main()
{
auto a = x();
a.someMemberFunction();
}
Why do you need a x_interface as global or static instance as you can get the instance of class x from anywhere at any time using static method : create_x_instance ?
I think best way to use it in class y is as :
(x::create_x_instance())->someMemberFunction();
Related
I wish to create a static Class object which should stay in the memory while the program is running. The object needs to be initialized only once by the init function and the output function will be called in a static method always. Does my code make sense and is it thread-safe?
class Singleton
{
public:
static void init(const int value)
{
static Singleton inst;
inst.Value = value;
}
static int prnValue()
{
return Value;
}
private:
Singleton() {};
static int Value;
};
int main()
{
int inputValue = 10;
Singleton::init(inputValue);
cout << Singleton::prnValue();
return 0;
}
New Edit:
Or can I try like this then?
class Singleton
{
public:
static Singleton& init(const int value)
{
static Singleton inst;
inst.Value = value;
return inst;
}
static int prnValue()
{
return Value;
}
private:
Singleton() {};
static int Value;
};
Addition:
Meyer's singleton example look like
class Singleton
{
public:
static Singleton& init()
{
static Singleton inst;
return inst;
}
private:
Singleton() {};
};
So Isn't my code consistent with Meyer's example?
Try4:
How about this?
class Singleton
{
public:
static Singleton& init(int value)
{
static Singleton inst(value);
return inst;
}
static int prnValue()
{
return Value;
}
private:
Singleton(value)
{
Value = value;
}
int Value;
};
Added comment:
How to pass argument in a singleton
seems to provide the same answer as Try4.
Abandon Singleton and make Value a const global variable initialized with a helper function.
Example:
// anonymous namespace to bind the global to this file to prevent the static
// initialization order fiasco
namespace
{
const int Value = ReadIniFile("section", "key", default_value);
}
But what if you need to use this variable in other files? The best advice I've got is don't. But if you must, the static initialization order fiasco needs to be overcome. Here's a quick way to do that that is similar to what you've seen so far:
// Lazy loader function similar to Meyers Singleton
int Value()
{
static int value = ReadIniFile("section", "key", default_value);
return value;
}
Usage:
me_function_need_Value(Value());
This ensures that Value is initialized before anyone can try to use it no matter which file in your project needs it. Unfortunately it's now hard to figure out when it goes out of scope, so the problem doesn't really go away. It's just moved from the start of the program to the end where it is a little more manageable. See Destruction order of static objects in C++ .
Ensure no one uses Value after main exits and you'll be safe. Still, use with caution.
I have a code below, i want to modify class's variables in static function but there is some error.
How can i fix it with "this" pointer?
There is no access to "this" pointer for static members in class,on the other hand I am trying to make an access to class variables in Static member function, therefore i am looking for a way to use "this" pointer of class "me" to do it.
class me {
public:
void X() { x = 1;}
void Y() { y = 2;}
static void Z() {
x = 5 ; y = 10;
}
public:
int x, y;
};
int main() {
me M;
M.X();
M.Y();
M.Z();
return 0;
}
I got this error :
invalid use of member ‘me::x’ in static member function.
You have two ways to do it :
Define your members as static if they are used in a static method.
Implement Dont use of static methods when class's members are non-static
Generally, the memory of static members or methods created once even when you dont create an object of your class. So you cannot use of a non-static members in a static method, because non-static members still have no memory While static methods have memory...
Try this :
public:
static void X() { x = 1;}
static void Y() { y = 2;}
public:
static int x;
static int y;
Dont forget to initialize static members :
int me::x = 0;
int me:y = 0;
You cannot use of this pointer inside a static method, because this may only be used inside a non-static member function. Notice the following :
this->x = 12; // Illegal use static `x` inside a static method
me::x = 12; // The correct way to use of `x` inside a static method
You can pass a pointer to an instance to the method:
class me {
public:
void X() { x = 1;}
void Y() { y = 2;}
static void Z(me* this_) { // fake "this" pointer
this_->x = 5 ;
this_->y = 10;
}
public:
int x, y;
};
int main() {
me M;
M.X();
M.Y();
M.Z(&M); // this works, but
// usually you call static methods like this
// me::Z(&M);
return 0;
}
You are trying to use a non-static member from a static member function. That's why it's giving you an error.
You can fix this by making the member function non-static (by removing static keyword). You could also make the variable static, so that your static member function can access it, but if you do so, the two other functions will still not compile.
Static method can access static members only.
class me {
public:
void X() { x = 1;}
void Y() { y = 2;}
static void Z() {
x = 5 ; y = 10;
}
public:
static int x, y;
};
int main() {
me M;
M.X();
M.Y();
M.Z();
return 0;
}
Adding to that #nivpeled said, think about this:
You may create several instances of me on your program. Which ones of the instances the static Z() method should modify?
I have the ultimate solution for you here lol.
I've asked this question so many time but instead of thinking or trying to solve the problem people starts judging my design which I think is funny.
So I have to explain that in some situations you will be in need to make static members gain access to non static ones, such case when you use a scripting interface in you program(Lua for example) that interface can only access static members of a class, which those members need to access to non static, anyways lets see how to do it.
class me {
public:
me() { This = this; } // Or you can assign it wherever you want
void X() { x = 1;}
void Y() { y = 2;}
static me* This; // Here is our "this" pointer :P
static void Z() {
This->x = 5 ; This->y = 10;
}
public:
int x, y;
};
//Remember to initialize it to avoid any linker's errors
me* me::This = nullpter; // or NULL or even 0
int main() {
me M;
// now you can access "this" pointer the usually way
M.X();
M.Y();
M.Z();
return 0;
}
After a while of thinking this is the most efficient solution i found.
I'm trying to declare a static object of a class A that I wrote in a different class B, like this:
class A // just an example
{
int x;
public:
A(){ x = 4; }
int getX() { return x; }
};
class B
{
static A obj1; // <- Problem happens here
public:
static void start();
};
int main()
{
B::start();
}
void B::start()
{
int x = obj1.getX();
}
What I want to achieve is to get int x in B::start() to equal int x in class A (4).
I tried googling all this for the past hour and all I understood was that C++ doesn't allow static objects' declarations. Is that correct?
If so, here's my question. How can I get the same result? What are my available workarounds? Keeping in mind that the rest of my code depends on the functions in class B to be static.
Error
error LNK2001: unresolved external symbol "private: static class A B::obj1"
Thanks!
You should initialize static var, the code:
class A // just an example
{
int x;
public:
A(){ x = 4; }
int getX() { return x; }
};
class B
{
static A obj1; // <- Problem happens here
public:
static void start();
};
A B::obj1; // init static var
int main()
{
B::start();
}
void B::start()
{
int x = obj1.getX();
}
As thinkerou said, you need to include the declaration of the variable:
A B::obj1;
For normal, non-static member variables you don't need this step because the variables are declared behind the scenes as part of the constructor. These variables are then tied to the instance of the class you just constructed. But static variables are not tied to any instance of a class; they are shared by all instances of a class. So constructors can't properly deal with them.
C++ gets around this by making you manually declare (and optionally initialize) any static member variables. Depending on where they are declared, they typically get constructed before your main() function starts, so they are available for use immediately.
I have a member function for a base class that I only want to be called [once] on the initialization of the first instance of the class (whether it be a direct instance of the base class, or an inherited class). Basically, I want to avoid unnecessary function calls.
A thing that is done only done during the first time something happens is the initialization of function local statics during the first execution of the surrounding function. So how you could do it:
class X {
static int firstInitFunc();
public:
X() {
static int onFirstCtorCall = firstInitFunc();
}
};
Now the first time you create an X, onFirstCtorCall will be initialized (threadsafe), calling the function. Any following creation of X won't call that function again.
If you have multiple constructors on X, you'll still want only one call to the function. You can achieve that by either delegating to the constructor with the static variable or by using another static function:
C++11:
class X {
static int firstInitFunc();
public:
X() {
static auto onFirstCtorCall = firstInitFunc();
}
X(int) : X() // delegate to X()
{ /* ... */ }
};
C++03:
class X {
static int firstInitFunc();
static void callFirstInit() {
static int onFirstCtorCall = firstInitFunc();
}
public:
X() {
callFirstInit();
}
X(int) {
callFirstInit();
}
};
Update: I'll pick up juanchopanza's comment and provide an example using std::call_once:
C++11 using call_once
class X {
static void firstInitFunc(); //see note to return types
static std::once_flag firstInitFlag;
public:
X() {
std::call_once(firstInitFlag, firstInitFunc);
}
X(int) {
std::call_once(firstInitFlag, firstInitFunc);
}
};
Note to return types: While in the case of function local statics' initialization used for the function call, that function must return a value, with wich the static will be initialized. In contrast, with std::call_once the function may not have a return type, because any returned value will not be evaluated.
Simple solution:
class C
{
private:
static bool runOnce;
public:
C()
{
if (!C::runOnce)
{
C::runOnce = true;
RunSth();
}
}
};
bool C::runOnce = false;
How do I store an object of a class within the class itself?
I know that I have to use the static keyword to accomplish what I want. Thus the class should look something like:
class my_class {
public:
static my_class instance;
my_class() {
my_class::instance = this
}
};
Below is the exact code as it appears in the class
namespace ArmISA {
class ISA {
protected:
static ISA* isa;
MiscReg miscRegs[NumMiscRegs];
const IntRegIndex *intRegMap;
.....
public:
ISA() {
ISA::isa = this;
...
}
...
};
}
The error I get is:
error: could not convert 'ArmISA::ISA::isa' from 'ArmISA::ISA*' to 'ArmISA::ISA'
my_class::instance = *this; will work, but I hope that you are aware that every time you create a new instance of the class, your instance member will be overwritten. Additionally, this means that instance is a copy of *this and not a reference - changes to one are invisible to the other.
Another option is to declare instance as a pointer, in which case both pointers refer to the same object and then instance = this; would compile:
static my_class* instance;
However, I am not sure what exactly you try to achieve.
this is a pointer. Use my_class::instance = *this.
To initialize a static member variable of non-integral type (or, in C++11, non-constexpr), do that outside the class.
For example:
struct Foo
{
static Foo bar;
double x_;
Foo( double x ): x_( x ) {}
};
// Preferably in an implementation file:
Foo Foo::bar( 3.14 );
The declaration outside the class is always formally the definition, which provides storage for the variable (needed if you ever take the address).
If you want to provide a header-file only module, one alternative is to provide access to the static variable via a function, like this:
struct Foo
{
static Foo& bar()
{
static Foo theBar( 3.14 );
return theBar;
}
double x_;
Foo( double x ): x_( x ) {}
};
Another technique is to inherit from a class template that provides the static variable.