jeudi 22 juillet 2021

std::shared_ptr not created from raw pointer

I am trying to create a singleton using std::shared_ptr. I'm pretty sure that I have most of it right, but I get a compiler error when I try to swap() a raw pointer into the smart pointer.

It works as expected when using std::make_shared instead, but that requires acrobatics to make it work with the private constructor.

I get this error:

error C2664: 'void std::shared_ptr<WndClass>::swap(std::shared_ptr<WndClass> &) noexcept': cannot convert argument 1 from 'WndClass *' to 'std::shared_ptr<WndClass> &'
message : see declaration of 'std::shared_ptr<WndClass>::swap'

This is the code for my singleton:

class WndClass {
public:
  static std::shared_ptr<WndClass> getInstance() {
    static std::weak_ptr<WndClass> instance;
    std::shared_ptr<WndClass> owned = instance.lock();
    if (!owned) {
      owned.swap(new WndClass());
      instance = owned;
    }
    return owned;
  }
  ~WndClass() {}

private:
  WndClass() {}
};

Aucun commentaire:

Enregistrer un commentaire