#include <SFML/Graphics.hpp>
#include <memory>
#include <map>
int main(int argc, char **argv)
{
std::map <const std::string, std::shared_ptr<sf::Texture> > resources;
sf::Texture tempResource;
tempResource.loadFromFile("1.PNG");
resources.insert(std::pair<const std::string, std::shared_ptr<sf::Texture>>("1", std::dynamic_pointer_cast<sf::Texture>( new sf::Texture(tempResource) ) ) );
return 0;
}
(新调用使用复制构造函数)
如果没有强制转换(只是调用 new 内部插入函数),它是行不通的。所以我使用 shared_ptr casting 来做到这一点,但是它不起作用。错误: 错误:没有用于调用“dynamic_pointer_cast(sf::Texture*)”的匹配函数
这里有什么问题,我该如何让它工作?我是 shared_ptrs 的新手,我自己无法解决。
谢谢
最佳答案
您要做的是从以前的非托管内存创建一个shared_ptr
。 dynamic_pointer_cast
不是完成这项工作的工具。相反,这应该有效:
resources.insert(std::pair<const std::string, std::shared_ptr<sf::Texture>>("1", std::shared_ptr<sf::Texture>(new sf::Texture(tempResource)));
//or:
resources.insert(std::make_pair("1", std::shared_ptr<sf::Texture>(new sf::Texture(tempResource)));
然而,从新分配的内存构造一个 shared_ptr
有点浪费。因为这会进行两次分配(一次用于内存,一次用于 shared_ptr
的内部数据)。如果您使用 std::make_shared(tempResource)
,这两个分配可以合并为一个以提高效率。
C++11 还允许 resources.emplace("1", std::make_shared(tempResource)
就地构造对,但上次我检查了编译器对此的支持是有点欠缺。
附带说明:如果您不再需要 tempResource
,您可能需要考虑移动(而不是使用 std::move(tempResource) 将其复制到数据结构中)
而不是 tempResource
来构造新分配的对象。根据 sf::texture
的实现,这可能(或可能不会)更有效。如果对象不是真正可移动构造的(因此移动构造基本上与拷贝相同),您可能希望将 Texture
直接构造为 shared_ptr
并调用 load关于那个:
auto tempResource = std::make_shared<sf::Texture>();
tempResource->loadFromFile("1.PNG");
resources.emplace("1",std::move(tempResource));//or insert if emplace isn't availible
关于c++ - 将普通指针转换到 std::shared_ptr 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13787429/