尝试使用 shared_ptr 创建单例时出现编译错误

Compile error when try to create singleton using shared_ptr

我尝试使用 shared_ptrs 创建单例对象。但是,当 constructors/destructor 对特定对象私有时,代码不会编译 密码是below.h

//ThreadPool.h
class ThreadPool
{
  public:
  static std::shared_ptr<ThreadPool> & getInstance();
  inline static std::shared_ptr<ThreadPool> m_threadPoolInstance;
  private:
  ThreadPool() =default;
~ ThreadPool() = default;
  ThreadPool(ThreadPool const  &) = default;
 };
 //ThreadPool.cpp
#include "pch.h"
#include <ThreadPool.h>

std::shared_ptr<ThreadPool> & ThreadPool::getInstance()
{
    if (! m_threadPoolInstance)
    {
        ThreadPool * p_ThreadPool = new ThreadPool();
        m_threadPoolInstance.reset(p_ThreadPool);
    }
    return m_threadPoolInstance;
}

我使用的是VS17编译器 创建的错误如下

error C2440: '': cannot convert from '_Ux *' to 'std::shared_ptr' with [ _Ux=ThreadPool ] include\memory(1462): note: No constructor could take the source type, or constructor overload resolution was ambiguous threadpool.cpp(9): note: see reference to function template instantiation 'void std::shared_ptr::reset(_Ux *)' being compiled with [ _Ux=ThreadPool ] threadpool.cpp(9): note: see reference to function template instantiation 'void std::shared_ptr::reset(_Ux *)' being compiled with [ _Ux=ThreadPool ]

当我在public段设置constructors/destructor时,编译成功。

但是运行同样的代码使用gcc编译器编译成功

转换失败,因为您的 ThreadPool class 有私有析构函数。

调用.reset(ptr)会使用delete表达式(delete ptr;)作为删除器,要求析构器为public.

此处参考重载(2):https://en.cppreference.com/w/cpp/memory/shared_ptr/reset

2-4) Replaces the managed object with an object pointed to by ptr. Y must be a complete type and implicitly convertible to T. Additionally:

2) Uses the delete expression as the deleter. A valid delete expression must be available, i.e. delete ptr must be well formed, have well-defined behavior and not throw any exceptions. Equivalent to shared_ptr(ptr).swap(*this);.

您需要创建析构函数 public 或提供自定义删除器。