Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this pointer of a static object

Tags:

c++

static

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?

like image 632
user1056903 Avatar asked Sep 17 '16 14:09

user1056903


People also ask

Can we use this pointer in static function?

'this' pointer is not available in static member functions as static member functions can be called without any object (with class name).

What is static pointer?

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.

What is a pointer to an object?

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.

What is a static object in C++?

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.


1 Answers

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.

like image 106
xinaiz Avatar answered Sep 28 '22 10:09

xinaiz