小编Atu*_*tul的帖子

如何删除Singleton指针?

我正在实现一个单例模式.在这里,我在GetInstance中创建一个新的Singleton*实例,当我尝试在析构函数中删除它时,它在无限循环中执行.在这种情况下如何避免内存泄漏?

请参考下面的代码:

#define NULL 0
class Singleton  
{ 
    private :  
        static Singleton* m_pInstance;  
        Singleton(){};  

    public :

    static Singleton* GetInstance()
    {
        if(m_pInstance == NULL)
        {
            m_pInstance  = new Singleton();         
        }
        return m_pInstance;
    }

    ~Singleton()
    { 
        //delete m_pInstance; // The system goes in infinate loop here if i uncomment this  
        m_pInstance = NULL;
    }
};

Singleton*  Singleton ::m_pInstance = NULL;   

int main()  
{
    Singleton* pInstance = Singleton::GetInstance();
    delete pInstance;  
}     
Run Code Online (Sandbox Code Playgroud)

c++ singleton

26
推荐指数
5
解决办法
4万
查看次数

std :: cout更改变量值

我正在编写我的函数正确返回指向引用的指针.我发现虽然函数返回了它想要做的事情,但是,std::cout正在修改结果.我在这里做错了吗?如何纠正这种行为?

请参阅以下代码段,

#include "stdafx.h"
#include <iostream>

using namespace std;
class MyClass
{
 public:
 MyClass(int x_):m_Index(x_){}
 int m_Index;
};

void myfunction(int *&currentIndex, MyClass obj)
{
 currentIndex = &obj.m_Index;
}

int _tmain(int argc, _TCHAR* argv[])
{
  MyClass obj(5);

  int *Index = NULL;
  myfunction(Index, obj);

  int curr_Index = *Index;
  cout << "Index = " << curr_Index << std::endl; // This works fine.
  cout << "Index = " << *Index << std::endl;     // This modifies *Index
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ pointers reference

3
推荐指数
2
解决办法
451
查看次数

0
推荐指数
2
解决办法
1078
查看次数

标签 统计

c++ ×3

pointers ×1

reference ×1

singleton ×1