dimanche 29 janvier 2023

'std::bad_weak_ptr' error while using shared_from_this

Note: Before posting the question, I have gone through the existing questions on std::bad_weak_error while using shared_from_this to pass the shared_ptr of the existing shared_ptr instance to another method. None of them are similar to this as:

  • There is already an existing shared_ptr instance of the class created before trying to call shared_from_this()
  • The class inherits from std::enable_shared_from_this<> publically.

Here is the sample code to reproduce the error:


#include <iostream>
#include <memory>

class ILogger {
public:
    virtual ~ILogger() {}

    virtual void Log() = 0;
};

class LogManager;

class Logger : public ILogger {
public:
    Logger(std::shared_ptr<LogManager> logManager)
        : m_logManager(logManager)
    {
    }

    void Log() override
    {
        std::cout << "Dump logs";
    }

private:
    std::shared_ptr<LogManager> m_logManager;
};

class ILogManager {
public:
    virtual ~ILogManager() {}

    virtual std::shared_ptr<ILogger> GetLogger() = 0;
};

class LogManager : public ILogManager, public std::enable_shared_from_this<LogManager> {
public:
    virtual std::shared_ptr<ILogger> GetLogger()
    {
        return std::static_pointer_cast<ILogger>(std::make_shared<Logger>(this->shared_from_this()));
    }
};

class LogManagerFactory {
public:
    static ILogManager* Create()
    {
        auto logManager = new LogManager();
        return logManager;
    }
};

int main()
{
    auto logManager = std::shared_ptr<ILogManager>(LogManagerFactory::Create());
    auto logger = logManager->GetLogger();
}

The error:

Program returned: 139
terminate called after throwing an instance of 'std::bad_weak_ptr'
  what():  bad_weak_ptr

Link to code: https://godbolt.org/z/GTcafM449

Aucun commentaire:

Enregistrer un commentaire