Chào mọi người. Theo em biết, khi cấp phát vùng nhớ sử dụng toán tử new cho con trỏ, thì bộ nhớ cấp phát vùng nhớ heap cho con trỏ. Em muốn hỏi là tại sao sử dụng singleton sử dụng toán tử new nhưng vùng nhớ không bị leak ạ (em đã thử check bằng valgrind). Chuyện gì sẽ xảy ra sau khi vùng nhớ bị leak, hệ điều hành có lấy lại nó không, hay nó bị mất luôn ạ. Mong mọi người giải đáp.
class Singleton
{
private:
Singleton()
{
}
static Singleton* s_instance;
std::string connection_string;
~Singleton()
{
}
public:
static Singleton* GetInstance()
{
if (s_instance == NULL)
{
s_instance = new Singleton();
}
return s_instance;
}
void SetConnectionString(const std::string& connection_string)
{
this->connection_string = connection_string;
}
std::string GetConnectionString()
{
return this->connection_string;
}
};
Singleton* Singleton::s_instance = NULL;
int main()
{
Singleton * properties = Singleton::GetInstance();
properties->SetConnectionString("http://127.0.0.1/");
std::cout << properties->GetConnectionString();
return 0;
}