使用 'this' 关键字初始化指针。它会创建新实例吗?使用它是否使我的程序线程安全?

Initializing a pointer with 'this' keyword. Does it create new instance? Using it make my program thread-safe or not?

这是一个单例设计模式。我正在尝试使用 thread_local 使给定的代码线程安全。 首先,我需要知道 'this' 指针的给定实例化是如何工作的。

File : Myclass.h

class Student
{
   public:
   Student();
   int x;
   private:
   static Student *globalStudent;

};


File : Myclass.cpp

Student *Student::globalStudent = NULL;

Student::Student()
{
    assert(globalStudent == NULL);
    globalStudent = this; // How this works? Does it creates an instance?
}

并且在使其成为线程安全之后,

File : Myclass.h

class Student
{
   public:
   Student();
   int x;
};

File : Myclass.cpp

thread_local Student *globalStudent = nullptr;

Student::Student()
{
    assert(globalStudent == NULL); 
    globalStudent = this; 
}

它能让我的程序线程安全吗?如果没有,那我该怎么办?

globalStudent = this; // How this works?

this 是一个特殊的表达式,它产生一个指向其成员函数被调用的对象的指针。这个赋值使得被赋值的指针指向被调用成员函数的对象。

Does it creates an instance?

不,分配指针不会创建实例。

DOES IT MAKE MY PROGRAM THREAD-SAFE?

单一的更改无法使整个程序线程安全。

但是,此更改确实可以安全地从多个线程调用 Student::Student() 而无需同步。然而,重要的是要考虑每个线程将指向不同的实例。因此,根据定义,这不是单例。

这是一种不必要的复杂方式来实现单例模式。 (而且singleton有时候也是一个anti-pattern,要慎重考虑是否合适)。