this pointer of a static object - c++

If I take this in an static object and store it in a vector in a Singleton object, can I assume the pointer points to the object during the whole lifetime of the program?

In general, you can't assume that, because order of static object creation in different translation units is unspecified. In this case it will work, because there is only single translation unit:
#include <iostream>
#include <vector>
class A
{
A() = default;
A(int x) : test(x) {}
A * const get_this(void) {return this;}
static A staticA;
public:
static A * const get_static_this(void) {return staticA.get_this();}
int test;
};
A A::staticA(100);
class Singleton
{
Singleton(A * const ptr) {ptrs_.push_back(ptr);}
std::vector<A*> ptrs_;
public:
static Singleton& getSingleton() {static Singleton singleton(A::get_static_this()); return singleton;}
void print_vec() {for(auto x : ptrs_) std::cout << x->test << std::endl;}
};
int main()
{
std::cout << "Singleton contains: ";
Singleton::getSingleton().print_vec();
return 0;
}
Output:
Singleton contains: 100
But what if A::staticA in defined in different translation unit? Will it be created before static Singleton is created? You can't be sure.

Related

Behavior of static variables in objects of derived classes [duplicate]

If I have something like
class Base {
static int staticVar;
}
class DerivedA : public Base {}
class DerivedB : public Base {}
Will both DerivedA and DerivedB share the same staticVar or will they each get their own?
If I wanted them to each have their own, what would you recommend I do?
They will each share the same instance of staticVar.
In order for each derived class to get their own static variable, you'll need to declare another static variable with a different name.
You could then use a virtual pair of functions in your base class to get and set the value of the variable, and override that pair in each of your derived classes to get and set the "local" static variable for that class. Alternatively you could use a single function that returns a reference:
class Base {
static int staticVarInst;
public:
virtual int &staticVar() { return staticVarInst; }
}
class Derived: public Base {
static int derivedStaticVarInst;
public:
virtual int &staticVar() { return derivedStaticVarInst; }
}
You would then use this as:
staticVar() = 5;
cout << staticVar();
To ensure that each class has its own static variable, you should use the "Curiously recurring template pattern" (CRTP).
template <typename T>
class Base
{
static int staticVar;
};
template <typename T> int Base<T>::staticVar(0);
class DerivedA : public Base<DerivedA> {};
class DerivedB : public Base<DerivedB> {};
They will share the same instance.
You'll need to declare separate static variables for each subclass, or you could consider a simple static map in which you could store variables that are referenced by derived classes.
Edit: A possible solution to this would be to define your base class as a template. Having a static variable defined in this template would mean that each derived class will have it's own instance of the static.
There is only one staticVar in your case: Base::staticVar
When you declare a static variable in a class, the variable is declared for that class alone. In your case, DerivedA can't even see staticVar (since it's private, not protected or public), so it doesn't even know there is a staticVar variable in existence.
The sample code given by #einpoklum is not working as it is because of the missing initialization of the static member foo_, missing inheritance in FooHolder declaration, and missing public keywords since we are dealing with classes. Here is the fixed version of it.
#include <iostream>
#include <string>
class A {
public:
virtual const int& Foo() const = 0;
};
template <typename T>
class FooHolder : public virtual A {
public:
const int& Foo() const override { return foo_; }
static int foo_;
};
class B : public virtual A, public FooHolder<B> { };
class C : public virtual A, public FooHolder<C> { };
template<>
int FooHolder<B>::foo_(0);
template<>
int FooHolder<C>::foo_(0);
int main()
{
B b;
C c;
std::cout << b.Foo() << std::endl;
std::cout << c.Foo() << std::endl;
}
I know that this question has already been answered but I would like to provide a small example of inheritance with static members. This is a very nice way to demonstrate the usefulness as well as what is happening with the static variables and the respective constructors.
FooBase.h
#ifndef FOO_BASE_H
#define FOO_BASE_H
#include <string>
class FooBase {
protected:
std::string _nameAndId;
private:
std::string _id;
static int _baseCounter;
public:
std::string idOfBase();
virtual std::string idOf() const = 0;
protected:
FooBase();
};
#endif // !FOO_BASE_H
FooBase.cpp
#include "FooBase.h"
#include <iostream>
int FooBase::_baseCounter = 0;
FooBase::FooBase() {
_id = std::string( __FUNCTION__ ) + std::to_string( ++_baseCounter );
std::cout << _id << std::endl;
}
std::string FooBase::idOfBase() {
return _id;
}
std::string FooBase::idOf() const {
return "";
} // empty
DerivedFoos.h
#ifndef DERIVED_FOOS_H
#define DERIVED_FOOS_H
#include "FooBase.h"
class DerivedA : public FooBase {
private:
static int _derivedCounter;
public:
DerivedA();
std::string idOf() const override;
};
class DerivedB : public FooBase {
private:
static int _derivedCounter;
public:
DerivedB();
std::string idOf() const override;
};
#endif // !DERIVED_FOOS_H
DerivedFoos.cpp
#include "DerivedFoos.h"
#include <iostream>
int DerivedA::_derivedCounter = 0;
int DerivedB::_derivedCounter = 0;
DerivedA::DerivedA() : FooBase() {
_nameAndId = std::string( __FUNCTION__ ) + std::to_string( ++DerivedA::_derivedCounter );
std::cout << _nameAndId << std::endl;
}
std::string DerivedA::idOf() const {
return _nameAndId;
}
DerivedB::DerivedB() : FooBase() {
_nameAndId = std::string( __FUNCTION__ ) + std::to_string( ++DerivedB::_derivedCounter );
std::cout << _nameAndId << std::endl;
}
std::string DerivedB::idOf() const {
return _nameAndId;
}
main.cpp
#include "DerivedFoos.h"
int main() {
DerivedA a1;
DerivedA a2;
DerivedB b1;
DerivedB b2;
system( "PAUSE" );
return 0;
}
If __FUNCTION__ is not working for you in your constructors then you can use something similar that can replace it such as __PRETTY_FUNCTION__ or __func__, or manually type out each class's name :(.
Alas, C++ has no virtual static data members. There are several ways to simulate this, more or less:
#GregHewgill's solution has you replicate the static variable in each derived class; this solution is simple, straightforward and doesn't introduce additional classes, but I don't like this one since it's verbose, and you have to be rather disciplined with it.
#MarkIngram suggested a CRTP-based solution, which saves you most of the typing; however, it messes up the inheritance structure, because what were previously subclasses of A are no longer really related as classes. After all, two templated types with the same name but different template arguments could be just any two types.
I suggest a different CRTP-based solution, using a mix-in class:
class A {
virtual const int& Foo() const = 0;
}
template <typename T>
class FooHolder {
static int foo_;
const int& Foo() const override { return foo_; }
}
class B : A, virtual FooHolder<B> { }
class C : B, virtual FooHolder<B> { }
The only thing you need to do in a subclass is also indicate the mix-in inheritance. There might be some virtual inheritance caveats I'm missing here (as I rarely use it).
Note that you either have to instantiate and initialize each subclass' static variable somewhere, or you can make it an inline variable (C++17) and initialize it within the template.
This answer was adapted from my answer to a dupe question.

Factory and singleton patterns: undefined reference

I have tried to understand what's going on in my situation from other questions in this site, but I haven't really found a good answer. I tried most of the suggestions I found but still get the same error.
I am trying to implement a factory based on a singleton and the CRTP. So I have a Singleton class, define in Singleton.h:
template<class T>
class Singleton
{
public:
static T &instance()
{
static T one;
return one;
}
Singleton(const Singleton &) = delete;
Singleton(Singleton &&) = delete;
Singleton &operator=(const Singleton &) = delete;
protected:
Singleton() = default;
};
I also have a Factory class, defined and implemented in Factory.h. The factory creates objects of a hierarchy whose base class is, for the purposes of this question, Object. These objects all have a constructor accepting a double.
class Factory : public Singleton<Factory>
{
friend class Singleton<Factory>; // to access constructor
public:
using createFunction = Object *(*)(double);
void registerObject(const std::string &, createFunction);
Object *createObject(const std::string &, double) const;
private:
Factory() = default;
std::map<std::string, createFunction> theCreatorFunctions;
};
void Factory::registerObject(
const std::string &ObjectId,
createFunction creatorFunction)
{
theCreatorFunctions.insert(
std::pair<std::string, createFunction>(
ObjectId, creatorFunction));
}
Object *Factory::createObject(
const std::string &ObjectId, double a) const
{
auto it = theCreatorFunctions.find(ObjectId);
if (it == theCreatorFunctions.end())
{
std::cout << ObjectId << " is an unknown object."
<< std::endl;
return nullptr;
}
return (it->second)(a);
}
Finally, I have a "helper" class that registers new types of Objects into the factory. Each time a new inherited object is created, say ObjectDerived, I add (in the .cpp file where ObjectDerived is implemented):
FactoryHelper<ObjectDerived> registerObjectDerived("ObjectDerived");
This creates an object of type FactoryHelper<ObjectDerived>, whose constructor handles the registration in the factory. FactoryHelper is defined (and implemented) in FactoryHelper.h:
template<class T>
class FactoryHelper
{
public:
FactoryHelper(const std::string &);
static Object *create(double);
};
template<class T>
FactoryHelper<T>::FactoryHelper(const std::string &ObjectId)
{
Factory &theFactory = Factory::instance(); // the one and only!
// if it doesn't exist at this point, it is created.
theFactory.registerObject(ObjectId, FactoryHelper<T>::create);
}
template<class T>
Object *FactoryHelper<T>::create(double a)
{
return new T(a);
}
So the problem that I have is that I get a bunch of undefined references to Factory::instance(), basically one for each type of object in the hierarchy.
If I put all in the same main.cpp file it works, but this is not a solution I'd like.
Since there is no compilation error when all your code is in one file, and you don't use any extern global objects that could cause issues with multiple files, I suspect that you have a problem in your compilation/linking script.
For the record, I can confirm that you have no intrinsic problem in the code. Adding a hierarchy
class Object
{
public:
Object(double _value) : value(_value) {}
virtual double getVal() { return value; }
private:
double value;
};
class SpecialObject : public Object
{
public:
SpecialObject(double _value) : Object(_value) {}
virtual double getVal() { double val = Object::getVal(); return val*val; }
};
the simple main routine
int main(int argc, char *argv[]) {
FactoryHelper<Object> baseMaker("Object");
FactoryHelper<SpecialObject> derivedMaker("SpecialObject");
Factory& factory = Factory::instance();
Object* a1 = factory.createObject("Object",4);
std::cout << a1->getVal() << std::endl;
Object* b1 = factory.createObject("SpecialObject",4);
std::cout << b1->getVal() << std::endl;
Object* c1 = factory.createObject("NonexistentObject",4);
return 0;
}
has the expected output:
4
16
NonexistentObject is an unknown object.
By the way, a matter of opinion: Your FactoryHelper<T> class does not achieve much, essentially acting as a shortcut for registering an object with the default allocator/constructor. At some point, making new classes stops actually saving much code. If you can use C++11, it's not much more difficult to write
factory.registerObject("SpecialObject", [] (double a) -> Object* { return new SpecialObject(a); });
If you wanted, you could add shortcut method to Factory itself:
// definition
template <class T>
void registerObject(const std::string &);
// implementation
template<class T>
void Factory::registerObject(const std::string &ObjectId)
{
registerObject(ObjectId, [] (double a) -> Object* { return new T(a); });
};
With this, the FactoryHelper class can be eliminated, and the equivalent main routine to before is
using namespace std;
int main(int argc, char *argv[]) {
Factory& factory = Factory::instance();
factory.registerObject<Object>("Object");
factory.registerObject<SpecialObject>("SpecialObject");
Object* a1 = factory.createObject("Object",4);
std::cout << a1->getVal() << std::endl;
Object* b1 = factory.createObject("SpecialObject",4);
std::cout << b1->getVal() << std::endl;
Object* c1 = factory.createObject("NonexistentObject",4);
return 0;
}
Again, if you are able to use C++11, you can always make createObject wrap the raw Object* pointer in a smart pointer (as you may well know, and maybe you have good reasons already for not doing this).

C++ - LNK 2019 Error, Trying to Define a Subclass Static Function

The call that generates the unresolved external symbol:
#include <string.h>
#include "GContext.h"
#include "GBitmap.h"
#include "GColor.h"
int main(int argc, char** argv) {
const int W = 100;
const int H = 100;
GContext* ctx = GContext::Create(W, H);
The abstract class method signature:
#ifndef GContext_DEFINED
#define GContext_DEFINED
#include "GTypes.h"
class GBitmap;
class GColor;
class GContext {
public:
GContext() {}
virtual ~GContext() {}
virtual void getBitmap(GBitmap*) const = 0;
virtual void clear(const GColor&) = 0;
static GContext* Create(const GBitmap&);
static GContext* Create(int width, int height);
};
#endif
And the Current Derived Class Implementation and Method Signature:
#include "GColor.h"
#include "GPixel.h"
#include "GBitmap.h"
#include "GContext.h"
#include "GTypes.h"
class myGContext : public GContext
{
public:
myGContext() : GContext(){}
static const GBitmap* bitmap;
void getBitmap(GBitmap* bitmap) const
{
}
void clear(const GColor& gcolor)
{
int length = sizeof( (GPixel)(bitmap->fPixels) ) / sizeof(GPixel);
for (int i = 0; i < length; i++)
{
(bitmap->fPixels)[i]
}
}
static GContext* Create(const GBitmap& gbitmap)
{
GContext::Create(gbitmap);
bitmap = &gbitmap;
GContext* g = new myGContext();
return g;
}
static GContext* Create(int width, int height)
{
GContext::Create(width,height);
GContext* g = new myGContext();
return g;
}
};
So I understand that I need to define both types of the function GContext::Create() to resolve the external symbol error, but I need to define them in my derived Class. Which I thought I was doing right, any ideas?
no Inheritance does not work, this is not like a virtual function.
I'm not exactly sure what you're trying to do but if you
Need to have static functions
Need both base and derived classes to have their own implementation
derived needs access to the base class' functions
this is all achievable:
#include <iostream>
class A {
public:
A() {}
static void f() { std::cout << "A f" << std::endl; }
};
class B : public A {
public:
B() {}
static void f() { std::cout << "B f" << std::endl; }
};
int main(int argc, char* argv[]) {
A a;
B b;
a.f();
b.f();
b.A::f();
return 0;
}
Output is
A f
B f
A f
I think it is just because you static method is not defined in your base class. From here it is said that LNK2019 can also occur when a static data member is declared but not defined.
Also, be careful when you try to redefine static methods inside subclasses:
You cannot override a static method in a subclass, you can only hide it.
And from the C++ standard:
9.4.1 Static member functions [class.static.mfct]
2/ A static member function shall not be virtual. There shall not be a static and a non-static member function with the same name and the same parameter types (13.1). A static member function shall not be declared const, volatile, or const volatile.
Example:
#include <iostream>
class Foo
{
public:
static void func() { std::cout << "Foo::func" << std::endl; }
};
class Bar : public Foo
{
public:
static void func() { std::cout << "Bar::func" << std::endl; }
};
int main(void)
{
Foo::func(); // Works
Bar::func(); // Works
Foo foo;
Bar bar;
foo.func(); // Works
bar.func(); // Works
bar.Foo::func(); // Works
Foo* foobar = new Bar;
foobar->func(); // Not the result expected
// Because no override.
return 0;
}

Shared variable among classes c++

I have multiple classes that need to share a single instance of another class. Publicly it should be unknown that this class exists. Is it appropriate to do something like the following? (Was tested as written)
#include <iostream>
class hideme
{
private:
int a;
public:
void set(int b) { a = b; }
void add(int b) { a += b; }
int get() { return a; }
hideme() : a(0) { }
};
class HiddenWrapper
{
protected:
static hideme A;
};
hideme HiddenWrapper::A;
class addOne : public HiddenWrapper
{
public:
void add() { A.add(1); }
int get() { return A.get(); }
};
class addTwo : public HiddenWrapper
{
public:
void add() { A.add(2); }
int get() { return A.get(); }
};
int main()
{
addOne a;
addTwo b;
std::cout << "Initialized: " << a.get() << std::endl;
a.add();
std::cout << "Added one: " << a.get() << std::endl;
b.add();
std::cout << "Added two: " << b.get() << std::endl;
return 0;
}
For what it's worth, hideme is part of a library I'm attempting to design a facade around, and the other classes have members from the library that interact with the static hideme.
Additionally, if the header file written for HiddenWrapper has no corresponding source file, is that the best place to define its static member? With an include guard.
Is there any other method to solve this problem? As far as I could imagine (not terribly far) I could only solve it otherwise with friendship, which I am wary of.
You can prevent access to a class by not making it accessible outside the translation unit that uses it.
// public_header.h
class A {
void bar();
};
class B {
void foo();
}
// private_implementation.cpp
#include "public_header.h"
namespace {
class hidden { void baz() {} };
hidden h;
}
void A::bar() {
h.baz();
}
void B::foo() {
h.baz();
}
This class will be usable only by A::bar and B::foo. The type hidden and the variable h still technically have external linkage, but no other translation unit can say their names.
Sometimes it is a better idea to inject shared ressources (by reference or pointer) through the constructor (also known as composition instead of inheritance). This way gives you the ability to share or not (e.g. to have a thread-safe variant of your code which is not). See http://de.wikipedia.org/wiki/Inversion_of_Control principle for more info.
This implements a singleton around some other class and hides it from
users:
class hideme {};
// fwd declarations
class x;
// library internal
class S
{
S() = delete;
S(S const&) = delete;
void operator=(S const&) = delete;
private:
static hideme& getInstance()
{
static hideme instance;
return instance;
}
friend x;
};
// library classes
class x {
hideme& s;
public:
x() : s(S::getInstance()) {}
};
int main()
{
x x;
return 0;
}
This does not handle cases where you actually want the hideme
instance to be destroyed when no other object is using it anymore. For
that you need to get a little bit more inventive using reference
counting.
I also should say that I think this is a bad idea. Singletons almost
always are.
Generally, the best approach, if you have a variable in the main part, and want to share it with all classes.
For example, if class X makes a change on this var, the change happened to the var in the main as well: you can use EXTEND
************************ The main *********************
#include <iostream>
using namespace std;
#include "Game.hpp"
//0: not specified yet; 1:singlemode; 2:multiplayerMode
int playingMode = 0;
int main()
{
Game game;
game.Run();
std::cout<< playingMode << std::endl;
return 0;
}
*********************** Class X *****************
#include <iostream>
using namespace std;
extern int playingMode;
....
....
if(m_isSinglePressed)
{
playingMode = 1;
...
}
else if(m_isMultiPressed)
{
playingMode = 2;
...
}

How to declare two different static variables? (C++)

EDIT: declaring them private was a typo, I fixed it:
Relating to another question, if I declared a static variable in a class, then derived a class from that, is there any way to declare the static variable as individual per each class. Ie:
class A:
{
public:
static int x;
};
class B:A
{
public:
const static int x;
};
does that define TWO DIFFERENT static variables x, one for A and one for B, or will I get an error for redefining x, and if I do get an error, how do a I create two seperate static variables?
When you're using static variables, it might be a good idea to refer to them explicitly:
public class B:A
{
public const static int x;
public int foo()
{
return B::x;
}
}
That way, even if the class "above" yours in the hierarchy decides to create a similarly-named member, it won't break your code. Likewise, I usually try to us the this keyword when accessing normal member fields.
Updated to use C++ syntax.
That creates two separate static variables.
Note that you have implicitly declared these private:
class A:
{
private:
static int x;
};
class B:A
{
private:
const static int x;
};
Which means the variables are not in competition with each other.
As already said, that creates two separate variables :
A::x;
// and
B::x;
In fact if you try to use just 'x' in a method of B, only the closer scope definition will be used until you are more precise :
#include <iostream>
class A
{
protected:
static int x;
public:
A() { x = 7; }
};
int A::x = 22;
class B:A
{
static const int x = 42;
public:
int a_x() const { return A::x; }
int b_x() const { return B::x; }
int my_x() const { return x; } // here we get the more local variable, that is B::x.
};
int main()
{
B b;
std::cout << "A::x = " << b.a_x() << std::endl;
std::cout << "B::x = " << b.b_x() << std::endl;
std::cout << "b's x = " << b.my_x() << std::endl;
std::cin.ignore();
return 0;
}
Outputs:
A::x = 7
B::x = 42
b's x = 42
Someone mentioned that accessibility might limit accessibility : making the base variable private will not make it accessible to the child class.
However, if the variable have to be protected or public, use an explicit access method or rely on the local scope rule I just demonstrated.
If you want a static variable that is individual to each class that uses A - you can use a template class.
For e.g.
template<class T> struct A
{
A() { ++s_var; }
static int s_var;
};
template<class T> int A<T>::s_var;
stuct B :A<B> {
B() { ++s_var; } // this is a different s_var than the one used by 'C' below
};
struct C : A<C> {
C() { ++s_var; } // this is a different s_var than the one used by 'B'
};