C++ 类终止

标签 c++ class events

我已经声明了一个类并实例化了一个类并期望它触发

~CLog();

但出于某种原因,它没有。有没有人看到任何明显的错误,为什么会发生这种情况?

我在一个结束的 void 中声明了这个类,所以我认为它应该触发。 我没有明确地销毁类,但我只是希望它自动超出范围并终止。

#pragma once
#include <fstream>
using namespace std;

class CLog 
{
  public:
    CLog(wstring filename);
    ~CLog();
    void WriteString(wstring uString);
  private:
    wofstream m_stream;
    wstring m_sPath;
};

#include "log.h";
#include "strhelper.h"

#include <fstream>
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>

wstring m_sText=L"";
wstring m_sPath=L"";

CLog::CLog(wstring uPath) 
{
    m_sPath=uPath;
}
void CLog::WriteString(wstring uString)
{
    m_sText+=uString;
    m_sText+=L"\n";
}
CLog::~CLog()
{

    if (FileExists(m_sPath))
    {
        DeleteFile(m_sPath);
    }

    //open for appending
    m_stream.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t,0x10ffff,std::generate_header>));
    m_stream.open(m_sPath,fstream::in | fstream::out | fstream::app); 

    m_stream << m_sText.c_str();

    m_stream.close();
}

我正在像这样使用 Clog

void foo() {
  wstring sLogPath;
  sLogPath=GetSpecialFolderDesktop() + L"\\load.log";
  CLog *pLog = new CLog(sLogPath);
  pLog->WriteString(L"Something);
}

我用的是VC2010。

最佳答案

您正在动态实例化 CLog。在这种情况下,您需要明确删除它。 如果您在堆栈 Clog log(sLogPath) 上创建它,则当对象超出范围时将调用析构函数。

关于C++ 类终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19137834/

相关文章:

c++ - try_lock() +unlock() 是检查 boost::interprocess::file_lock 是否被锁定的有效方法吗?

python - "Cannot convert Python object argument to type ' <typename> '"- 使用 Cython 包装 C++ 类时出错

c++ - 类模板 - 从 "box"对象中删除项目

c++ - 对于类构造函数,通过括号或等号赋值有什么区别?

java - 如何禁用 imageview 事件?

Javascript dispatchEvent - 如何更改 eventArgs

c++ - 模板导出麻烦

c++ - 对于每个模板类型,一个集合类型的参数

ios - 如何快速从协议(protocol)转换/转换为类?

java - 使用 AWT 按钮并检测是否被单击