0

Thanks to anyone willing to help:

I am trying to create a Singleton class in C++ and I am new to the language. My scrum team methods say we should only use shared pointers. However, when I am trying to pass constructor into my Singleton object (shared pointer) I am getting error such as "binary '=' : no operator found which takes a right hand operand...". Basically non-compatible type conversion. Providing necessary code below:

//Singleton getter class
std::shared_ptr<LibMouse3d::LibCoreMouse3d::DeviceHandle> LibMouse3d::LibCoreMouse3d::DeviceHandle::getInstance(){

    if(device == NULL){

        //trying pass constructor into shared pointer object
        device = LibMouse3d::LibCoreMouse3d::DeviceHandle();
    }

    return device;
}

This is my constructor:

LibMouse3d::LibCoreMouse3d::DeviceHandle::DeviceHandle() {

    this->InitDevice();
}

And the object in header file

//singleton object - device
std::shared_ptr<DeviceHandle> device;

Thanks for any effort and sorry if I forgot something or added non-relevant info. This is my first question here, I could not google myself into answer for some time and I don't want my scrum master to be worried about my progress.

Michal Fašánek
  • 513
  • 5
  • 17
  • 2
    Well, if it's a _singleton_ you don't ever need to have a _shared_ pointer – user3159253 Nov 25 '15 at 23:59
  • Think of a singleton as a global variable with a delayed construction. – user3159253 Nov 26 '15 at 00:01
  • Withholding my opinion on the use of `shared_ptr`, you should not be using `NULL`. Use `nullptr` if you need a null value, but with smart pointers (and raw pointers), `if (!device)` is fine. – chris Nov 26 '15 at 00:03
  • This should probably return `weak_ptr` rather than `shared_ptr`. Or use `unique_ptr` and return reference. – M.M Nov 26 '15 at 00:13
  • 2
    [Singleton does not require pointers.](http://stackoverflow.com/a/271104/315052) – jxh Nov 26 '15 at 00:31

1 Answers1

2

You're not passing the constructor. In fact, there is currently no way to pass a constructor in C++. You're assigning a temporary DeviceHandle object to device. However, some documentation makes it apparent that there is no assignment operator taking a T. For that matter, it also doesn't have an assignment operator that would take a function-like thing (like a constructor).

Instead, smart pointers have reset:

device.reset(new DeviceHandle());
chris
  • 60,560
  • 13
  • 143
  • 205