3

the result of the code below is Unknown error -1.

widget.h:

#ifndef WIDGET_H_
#define WIDGET_H_

#include <memory>

class widget
{
public:
    static widget& get_instance();

private:
    static std::unique_ptr<widget> instance;
};

#endif

widget.cpp:

#include <mutex>
#include <thread>
#include "class.h"

std::unique_ptr<widget> widget::instance;
std::once_flag is_create;

widget& widget::get_instance()
{
    std::call_once(is_create, [=]{ instance = std::make_unique<widget>(); });
    return *instance;
}

main.cpp:

#include "widget.h"
#include <iostream>
#include <exception>

int main(int argc, char* argv[]) 
{
    try
    {
        widget::get_instance();
    }
    catch (std::system_error e)
    {
        std::cout << e.what() << std::endl;
    }

    return 0;
}

this says that

std::system_error if any condition prevents calls to call_once from executing as specified

Is this means make_unique failed ?

I trun to gdb and it seems that something wrong in if (__gthread_active_p ()) line and __gthread_active_ptr == 0. I cannot understand that

why it will throw this exception.

longack
  • 105
  • 7
  • 2
    Did you compile/link with the `-pthread` option (assuming this is `g++` or `clang++`)? – G.M. Aug 05 '20 at 14:59
  • Oh, you are right. It fixed after I add `pthread` flag. Interesting, I don't meet link problem. – longack Aug 05 '20 at 15:09

0 Answers0