【问题标题】:C++ class terminationC++ 类终止
【发布时间】:2013-10-02 13:17:03
【问题描述】:

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

~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
  • ~CLog() 仅在变量超出 IIRC 范围时运行
  • 什么是I declared the class within a void that ends??
  • void foo() { wstring sLogPath; sLogPath=GetSpecialFolderDesktop() + L"\\load.log"; CLog *pLog = new CLog(sLogPath); pLog->WriteString(L"Something); }

标签: c++ class events


【解决方案1】:

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

【讨论】:

  • 虽然 OP 最初并未发布相关代码,但完全可以预见这就是原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
  • 2011-01-15
  • 2014-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多