所以,这是我的课程及其功能:
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
谢谢!
答案 0 :(得分:3)
Boost :: shared_ptr将支持自1.53版以来std :: nullptr_t的构造函数。
答案 1 :(得分:2)
这将适用于std :: shared_ptr而不是boost :: shared_ptr我认为
答案 2 :(得分:2)
根据http://www.boost.org/doc/libs/1_52_0/libs/smart_ptr/shared_ptr.htm#Members,boost::shared_ptr
无法通过空指针常量进行初始化,因为对于指针构造函数,它由Y*
模板化,其中Y
是模板参数。在推导Y*
时,不会考虑将空指针常量转换为Y*
,因此构造函数将具有推导失败,并在传递nullptr
时被忽略。
但std::shared_ptr
可以接受它,因为它有std::nullptr_t
重载,所以如果你愿意,你可以切换。
请注意,传递nullptr
与传递空指针(T*)nullptr
不同。后者不会使用constexpr
构造函数,但前者会(除其他差异外)。因此,在前一种情况下,如果指针是命名空间范围变量,则它具有常量初始化,并且不会在其他转换单元中引发具有命名空间范围对象的初始化竞争。