【问题标题】:boost::shared_ptr and nullptr in default template function argument默认模板函数参数中的 boost::shared_ptr 和 nullptr
【发布时间】:2012-12-09 11:48:53
【问题描述】:

所以,这是我的课程及其功能:

template <class T>
class cResourceManager
{
public:
    bool add(const std::string & key, boost::shared_ptr<T> ptr = nullptr); 
private:
    std::map <const std::string, boost::shared_ptr<T> > resources;
};

template <class T>
bool cResourceManager<T>::add(const std::string & key, boost::shared_ptr<T> ptr)
{
    if (resources.find(key) == resources.end())
    {
        if(ptr != nullptr) //we have the object
        {
            resources.insert(std::pair<const std::string, boost::shared_ptr<T>>(key, ptr));
        return true;
    }
    else //we need to load object using sfml loadFromFile
    {
        T tempResource;
        tempResource.loadFromFile(key);
        resources.insert(std::pair<const std::string, boost::shared_ptr<T>>(key, new T(tempResource)));
        if(resources[key] == nullptr) return false;
        else return true;
    }
}
}     

该类在静态库中,它编译没有问题。但是,当我在正常应用中使用它时:

cResourceManager<sf::Texture> resourceManager;
resourceManager.add("1.PNG");

我得到错误: 错误:“boost::shared_ptr”类型参数的默认参数类型为“std::nullptr_t”

我不知道这里出了什么问题,shared_ptr 不能有 nullptr 值吗? 我使用 g++ 4.7 和 -std=c++11

谢谢!

【问题讨论】:

    标签: c++ boost c++11 shared-ptr


    【解决方案1】:

    Boost::shared_ptr 从 1.53 版开始支持 std::nullptr_t 的构造函数。

    【讨论】:

      【解决方案2】:

      我认为这将适用于 std::shared_ptr 而不是 boost::shared_ptr

      【讨论】:

      • shared_ptr 现在是否符合 c++11 标准?第二个问题,boost::shared_ptr 是否有某种 nullptr 关键字?
      【解决方案3】:

      根据http://www.boost.org/doc/libs/1_52_0/libs/smart_ptr/shared_ptr.htm#Membersboost::shared_ptr 不能用空指针常量初始化,因为对于带指针的构造函数,它是由Y* 模板化的,其中Y 是模板参数。推导Y*时不考虑将空指针常量转换为Y*,因此构造函数会出现推导失败,在传递nullptr时会被忽略。

      std::shared_ptr 可以接受,因为它有std::nullptr_t 过载,所以如果你愿意,你可以切换。

      请注意,传递nullptr 与传递像(T*)nullptr 这样的空指针不同。后者不会使用 constexpr 构造函数,但前者会(以及其他差异)。因此,在前一种情况下,如果您的指针是命名空间范围变量,它具有常量初始化,并且不会引发与其他翻译单元中的命名空间范围对象的初始化竞争。

      【讨论】:

      • 谢谢!所以我会切换到 std::shared_ptr
      • @user1873947 或者,您可以传递默认构造的 boost::shared_ptr 或在 C++11 中(这是使用 std::shared_ptr 的先决条件),您可以将 {} 作为函数参数传递,如果您想避免将 boost::shared_ptr 的所有实例更改为 std::shared_ptr
      • 我将完全切换到 std::shared_ptr。但是,带有 std::shared_ptr 声明的文件是什么?我找不到它,我得到“std::shared_ptr' has not been declared”
      猜你喜欢
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-26
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      相关资源
      最近更新 更多