【发布时间】:2017-10-16 09:16:51
【问题描述】:
我需要在我的模板化单例类中使用 std::call_once 但目前下面的示例代码未编译:
std::once_flag flag;
class LifeTrackerHelper
{
public:
template<class T>
inline static int SetLongevity(std::unique_ptr<T>& pobj,unsigned int longevity = 0)
{
return 0;
}
};
template<class T>
class Singleton
{
public:
inline static T* getInstance()
{
static std::unique_ptr<T> ptr(new T());
std::call_once(flag,&LifeTrackerHelper::SetLongevity<T>,ptr);
//static int i = LifeTrackerHelper::SetLongevity<T>(ptr);
// if call_once is commented and above line uncommented this will work
return ptr.get();
}
};
class Test
{
public:
void fun()
{
std::cout<<"Having fun...."<<std::endl;
}
};
int main()
{
Singleton<Test>::getInstance()->fun();
}
因此需要帮助了解如何在此处正确使用 std::call_once。
【问题讨论】:
-
为什么-1,问题有什么问题吗??
-
flag的声明在哪里?你到底想在这里做什么? -
感谢我在示例中添加了标志,我只是想修改我的同事创建的通用单例
-
问题是
ptr传递给call_once。我假设call_once将尝试调用std::unique_ptr的复制构造函数,这将导致错误,因为std::unique_ptr的复制构造函数被删除。不过我还没有测试过。 -
我尝试在 unique_ptr 上使用 std::ref 但这也不起作用
标签: c++ multithreading c++11 c++14