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?
'this' pointer is not available in static member functions as static member functions can be called without any object (with class name).
A static pointer can be used to implement a function that always returns the same buffer to the program. This can be helpful in serial communication.
A pointer is a type of variable that carries location information. In this case, the example variable will store the address of an Order object that we want to interact with. We initialize the pointer variable by using the C++ new operator to construct a new object of type Order.
Static object is an object that persists from the time it's constructed until the end of the program. So, stack and heap objects are excluded. But global objects, objects at namespace scope, objects declared static inside classes/functions, and objects declared at file scope are included in static objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With