c++ - 使用boost shared_ptr时使用默认参数

标签 c++ boost shared-ptr

我有 boost shared_ptr 作为函数的参数,我希望这个参数有一些默认值。

void foo(boost::shared_ptr<myclass> ptr = nullptr);

因为ptr不是一个指针,而是一个类..

那我该怎么办?

我发现了一个类似的问题: boost::shared_ptr and nullptr in default template function argument

但是那里的解决方案只是切换到std::shared_ptr,但我做不到

谢谢

最佳答案

由于您使用的是 nullptr,因此您必须使用 C++11,因此您应该能够这样做:

void foo(boost::shared_ptr<myclass> ptr = {});

这使得默认参数成为默认构造的 shared_ptr,与使用 nullptr 初始化的参数相同。它要求您的编译器支持统一的初始化语法,而不是要求您的 Boost 版本支持从 nullptr_t 构造 shared_ptr

如果您的编译器无法处理,请使用 ForEveR 的答案。

关于c++ - 使用boost shared_ptr时使用默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17321287/

相关文章:

c++ - 随机高斯函数的时间复杂度

c++ - 带 shared_ptr 的二维数组

c++ - boost::shared_ptr 循环依赖

C++ Push_back复制对象而不是引用

c++ - 填充闭合二维曲线的算法

C++,插入 List<Class*>,vector<Class> 迭代器

c++ - Mongodb C++ 驱动程序 - 链接错误:使用已弃用的 boost::stystem::get_generic_category()

c++ - 将参数传递给 boost::thread 没有重载函数需要 2 个参数

c++ - 如何 boost::bind 以通用引用作为参数的模板成员函数

c++ - 按值或 const ref 传递 std::shared_ptr 然后存储在容器中?