Saturday, April 27, 2013

c++: header include order, std::string and <string>

 

A friend of mine wrote these 3 files

Singleton.h:

#pragma once
#include <fstream>
#include <string>

class Singleton
{
private:
    std::ofstream m_stream;
    Singleton(void);
    static bool instance;
    static Singleton* s;
public:
    ~Singleton(void);
    static Singleton* getInstance();
    void write(std::string c);
    void close();
};

Singleton.cpp

#pragma once

#include "Singleton.h"
#include "Constants.h"

Singleton* Singleton::s = NULL;
bool Singleton::instance = false;

Singleton::Singleton(void)
{
    const char* cs = LOG_ALL_FILE_PATH.c_str();
    m_stream.open(cs);
}

Singleton::~Singleton(void)
{
    m_stream.close();
}

Singleton* Singleton::getInstance() {
    if (!instance){
        s = new Singleton();
        instance = true;
    }
    return s;
}

void Singleton::write(std::string logline){
    m_stream << logline << std::endl;
}

void Singleton::close(){
    if (instance)
        m_stream.close();
}

Constant.h

/** Log file path */
const std::string LOG_ALL_FILE_PATH = "file.log";

If we change

#include "Singleton.h"
#include "Constants.h"

to

#include "Constants.h”

#include "Singleton.h"

it will not compile

Which let me to believe that

std::string can not appear before the 1st #include <string>

No comments:

Post a Comment