문제

I'm trying to implement a singleton-like object with C++11. I got this example from another user.

It creates an object with the constructor and the copy constructor private and default, as well as an instance() function to return static object.

As I understand this should prevent the creation of two instances of this object. But as you can see in my main.cpp, I create two instances and it compiles and runs.

Is my object creation wrong or what? I don't get it.

object.hpp:

#ifndef OBJECT_H
#define OBJECT_H

#include <iostream>
using namespace std;

class Object
{
private:
   Object() = default;
   Object(const Object&) = delete;
public:
   // Singleton in C++11
   static Object& instance() { static Object z; return z; }
};

#endif // OBJECT_H

main.cpp:

#include "object.hpp"

int main() 
{
    Object* object = new Object();
    object->instance();

    Object* object2 = new Object();
    object->instance();

    return 0;
}
도움이 되었습니까?

해결책 2

First your code in main won't compile. Object default constructor is private, so you won't be able to do :

Object* object = new Object();

Second, as instance() is static (means not related to any instance) there is no need to call it from an object, the class name suffices :

Object& theInstance = Object::instance();

Finally, the code of instance is :

static Object& instance()
{
    static Object z;
    return z;
}

It's OK. A static variable in a C++ function means that the object is instanciated once : when the function is ran for the first time. Then z won't be destroyed at the end of the function (contrary to other so-called local variables) and will be re-used for next calls of instance.

So at first call of instance :

  • z is created
  • z z is returned

At next calls :

  • z is returned

A singleton is a class which implies only one instance will be created. You can verify the objects are the same with :

Object& a = Object::instance();
Object& b = Object::instance();

std::cout << &a << std::endl;
std::cout << &b << std::endl;

a and b should have the same memory adress.

This is the expected behaviour of a singleton : if the object construction function (instance) is called several times, the same instance will be returned.

So as you said, instance actually prevents the creation of two Object. Maybe you expected you program to return some error on the second call of instance. If you wan't this behaviour, you'll have to make it yourself using expections or returning NULL. Yet, The code you wrote shows the classic way singletons are done in C++.

다른 팁

When I try to compile your code, I get a proper error from the compiler:

main.cpp: error: calling a private constructor of class 'Object' Object* ob1= new Object() ;

So I would not be able to create two objects using new.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top