c++ - 静态对象的this指针

标签 c++ static

如果我在静态对象中获取 this 并将其存储在 Singleton 对象的 vector 中,我可以假设指针在程序的整个生命周期内都指向该对象吗?

最佳答案

一般来说,您不能这样假设,因为在不同翻译单元中静态对象的创建顺序是未指定的。在这种情况下它会起作用,因为只有一个翻译单元:

#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;
}

输出:

Singleton contains: 100

但是如果 A::staticA 在不同的翻译单元中定义怎么办?它会在 static Singleton 创建之前创建吗?你不能确定。

关于c++ - 静态对象的this指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39548118/

相关文章:

java - 在嵌套静态类 java 中使用 "this"关键字

c++ - AVL 树中的比较由指向对象的指针组成

c++ - 我的 QTreeWidgetIcons 在哪里?

c++ - 对类中结构的 C++ vector 进行排序

c - 递归和静态变量

c - C 编程中的访问指针

c++ - 文件线程

c++ - 禁用 Visual Studio 自动完成

express - 在 Express 中提供静态文件不起作用

c# - 静态方法总是保存在内存中吗?