简体   繁体   中英

CRTP with unique_ptr causes segfault

I'm using CRTP design pattern to implement logging mechanism for my project. Base CRTP class looks like this:

#include <fstream>
#include <memory>
#include <mutex>
#include <iostream>
#include <sstream>

template <typename LogPolicy>
class Logger
{
  public:
    template <typename... Args>
    void operator()(Args... args)
    {
        loggingMutex.lock();
        putTime();
        print_impl(args...);
    }

    void setMaxLogFileSize(unsigned long maxLogFileSizeArg)
    {
        //if (dynamic_cast<FileLogPolicy *>(policy.get()))
        //    policy->setMaxLogFileSize(maxLogFileSizeArg);
    }

    ~Logger()
    {
        print_impl(END_OF_LOGGING);
    }

  protected:
    std::stringstream buffer;
    std::mutex loggingMutex;
    std::string d_time;
  private:
    static constexpr auto END_OF_LOGGING = "***END OF LOGGING***";

    void putTime()
    {
        time_t raw_time;
        time(&raw_time);
        std::string localTime = ctime(&raw_time);
        localTime.erase(std::remove(localTime.begin(), localTime.end(), '\n'), localTime.end());
        buffer << localTime;
    }

    template <typename First, typename... Rest>
    void print_impl(First first, Rest... rest)
    {
        buffer << " " << first;
        print_impl(rest...);
    }

    void print_impl()
    {
        static_cast<LogPolicy*>(this)->write(buffer.str());
        buffer.str("");
    }
};

One of the concrete logging class is logging to file, which looks like this:

#include "Logger.hpp"

class FileLogPolicy : public Logger<FileLogPolicy>
{
  public:
    FileLogPolicy(std::string fileName) : logFile(new std::ofstream)
    {
        logFile->open(fileName, std::ofstream::out | std::ofstream::binary);
        if (logFile->is_open())
        {
            std::cout << "Opening stream with addr " << (logFile.get()) << std::endl;
        }
    }

    void write(const std::string content)
    {

        std::cout << "Writing stream with addr " << (logFile.get()) << std::endl;
        (*logFile) << " " << content << std::endl;
        loggingMutex.unlock();
    }

    virtual ~FileLogPolicy()
    {
    }

  private:
    std::unique_ptr<std::ofstream> logFile; //Pointer to logging stream
    static const char *const S_FILE_NAME;   //File name used to store logging
    size_t d_maxLogFileSize;         //File max size used to store logging
};

Basically I create object of policy class and would like to log stuff, depending on the policy chosen. So for example I create logger like this:

FileLogPolicy log("log.txt");

In this case it should use Logger to save logs to file, by calling static_cast<LogPolicy*>(this)->write(buffer.str()) . Apparently calling write function works fine but stream object is changing to null. How is that possible if FileLogPolicy destructor has not been called yet? When I change logFile to be normal pointer all works well. I don't get it where is the difference.

~Logger()
{
    print_impl(END_OF_LOGGING);
}

this code runs after the descendend class has been destroyed.

void print_impl()
{
    static_cast<LogPolicy*>(this)->write(buffer.str());
    buffer.str("");
}

it then casts this to be a pointer to a class that this is no longer.

The unique ptr is gone, and even accessing the member is UB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM