Hi, I'm having trouble putting an sf::Sprite inside of a unique pointer.
The following code will compile just fine without warnings or errors:
void SpriteManager::attachSprite(sf::Sprite sprite)
{
Ptr p;
mSprites.push_back(std::move(p));
}
Ptr is a typedef to this:
typedef std::unique_ptr<sf::Sprite> Ptr;
When I try to construct a Ptr p with a sf::Sprite like this, however, I get an error.
void SpriteManager::attachSprite(sf::Sprite sprite)
{
Ptr p(sprite);
mSprites.push_back(std::move(p));
}
1>SpriteManager.cpp(12): error C2664: 'std::unique_ptr<_Ty>::unique_ptr(std::nullptr_t)' : cannot convert parameter 1 from 'sf::Sprite' to 'std::nullptr_t'
Which I don't really understand, because I thought arguments taken from a unique_ptr's constructor defined their pointer. If someone could help address this issue, that'd be great.
Thanks!
Try:
using Ptr = std::unique_ptr<sf::Sprite>;
void SpriteManager::attachSprite(std::Sprite sprite)
{
Ptr p{new sf::Sprite{sprite}};
mSprites.push_back(std::move(p));
}
When your compiler already supports C++14, you don't even need to mention new:
auto ptr = std::make_unique<sf::Sprite>(sprite);
mSprites.push_back(std::move(ptr));
But why do you store sprites in unique pointers? Why this indirection if you don't use inheritance?
std::vector<sf::Sprite> would be simpler and probably more efficient.