PDA

View Full Version : Side effect to const static variable - do not know how



Prototyp144
4th June 2013, 14:25
Hey there guys,

i got a runtime error in this function here:


#include "logger.h"

#include <QApplication>
#include <QDebug>

QString Logger::pathToLog = "";

const QString Logger::streamFiles[] = {
"out.log", /// LS_STD
"database.log", /// LS_DB
"error.log" /// LS_ERR
};

bool Logger::writeLog(LoggerStream stream, const QString &msg)
{
if (msg.isEmpty() || stream < 0 || stream >= LS_LAST)
return false;

QString str;
QFile * f;
QDir * d;

str = DTime::dTimeToStr(QDateTime::currentDateTime());
str.append(" : ");
str.append(msg);
str.append("\n\r");

if (pathToLog == "") {
d = new QDir(qApp->applicationDirPath());
if (!d->cd("data"))
if (!d->mkdir("data") || !d->cd("data"))
return false;
pathToLog = d->path();
}

switch (stream) {
default : /// falls through
case LS_STD:
f = new QFile(pathToLog + QDir::separator() + streamFiles[LS_STD]);
if (f->open(QIODevice::Append | QIODevice::Text)) {
qWarning() << "filename = " + f->fileName();
f->write(str.toAscii());
f->close();
return true;
}
break;
case LS_DB :
f = new QFile(pathToLog + QDir::separator() + streamFiles[LS_DB]);
if (f->open(QIODevice::Append | QIODevice::Text)) {
qWarning() << "filename = " + f->fileName();
f->write(str.toAscii());
f->close();
return true;
}
break;
case LS_ERR:
f = new QFile(pathToLog + QDir::separator() + streamFiles[LS_ERR]);
if (f->open(QIODevice::Append | QIODevice::Text)) {
qWarning() << "filename = " + f->fileName();
f->write(str.toAscii());
f->close();
return true;
}
break;
}

return false;
}



#ifndef LOGGER_H
#define LOGGER_H

#include "dtime.h"

#include <QDir>
#include <QFile>

class Logger
{
public:
enum LoggerStream {
LS_STD = 0,
LS_DB,
LS_ERR,
LS_LAST
};

static bool writeLog(LoggerStream stream, const QString &msg);

private:
static QString pathToLog;
static const QString streamFiles[LS_LAST];
};

#endif // LOGGER_H


Every time i write to any output stream, all goes right. But when finishing the application, that means destruct my Database class, calling the logger from it's destructor, writes the output to the file "database.loŀ". Very strange...

Anyone sees the fault? I hope all the needed information are here. Thanks for a helpfull reply!

Regards