lundi 22 janvier 2018

Is using new thread safe to instantiate a singleton in an implementation similar to Scott Meyer's singleton idiom?

I came over this question recently, and got doubts about the Instance() function implementation:

class Configuration
{
public:
    static Configuration* Instance() {
        static Configuration * myInstance = new Configuration();
        return myInstance;
    }

    int i;
    // delete copy and move constructors and assign operators
    Configuration(Configuration const&) = delete;             // Copy  construct
    Configuration(Configuration&&) = delete;                  // Move construct
    Configuration& operator=(Configuration const&) = delete;  // Copy assign
    Configuration& operator=(Configuration &&) = delete;      // Move assign

protected:
    Configuration() {

    }
    ~Configuration() {}

    // ...
}

Unfortunately the OP doesn't seem to be able to provide an [MCVE] that reproduces that read access violation they claim.

  • Is using an instance pointer and new in that implementation still guaranteed to be thread safe (a race condition could be a potential reason for that error)?

Aucun commentaire:

Enregistrer un commentaire