[英]C++ class termination
I have declared a class and instantiated a class in one and expected it to fire 我已经声明了一个类并实例化了一个类,并期望它会触发
~CLog();
But for some reason, it does not. 但是由于某种原因,事实并非如此。 Does anybody see any obvious errors why this could happen? 有人看到为什么会发生这种错误吗?
I declared the class within a void that ends, so it SHOULD fire, I think. 我在一个空虚的地方声明了该类,所以我认为它应该触发。 I do not destroy the class explicitely, but I simply expected it to go out of out scope automatically and terminate. 我没有明确地销毁该类,但我只是希望它会自动超出范围并终止。
#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();
}
I am using Clog
like this 我正在像这样使用Clog
void foo() {
wstring sLogPath;
sLogPath=GetSpecialFolderDesktop() + L"\\load.log";
CLog *pLog = new CLog(sLogPath);
pLog->WriteString(L"Something);
}
I am using VC2010. 我正在使用VC2010。
You are instantiating dynamically the CLog
. 您正在动态实例化CLog
。 In that case, you need to delete it explicitly. 在这种情况下,您需要明确删除它。 If you create it on the stack Clog log(sLogPath)
, the destructor will be called when the object goes out of scope. 如果在堆栈Clog log(sLogPath)
上创建它,则在对象超出范围时将调用析构函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.