Zack Stewart
Zack Stewart

Reputation: 327

C++ auto_ptr and shared_ptr changes from VC++10 to VC++12

I'm working on updating a codebase from Visual Studio and C++10 to VS/C++12

I've hit a sticking point relating to shared_ptr and auto_ptr.

The code in the original C++10 is

void CommandLoader::RegisterCommand(std::auto_ptr<ILoadableCommand> cmd)
{
assert(cmd.get() != NULL);
m_pImpl->m_registered.push_back(shared_ptr<ILoadableCommand>(cmd));
}

the compile error is :

error C2440: '<function-style-cast>' : cannot convert from std::auto_ptr<ILoadableCommand>' to 'std::shared_ptr<ILoadableCommand>'

And inside the editor, it complains that

Error: no instance of constructor"std::shared_ptr<_Ty> matches the argument list.

My guess is that auto_ptr is no longer being accepted as a parameter to the constructor of shared_ptr, but http://msdn.microsoft.com/en-us/library/bb981959.aspx says otherwise.

I'm at a little bit of a loss, so any help would be great!

Upvotes: 0

Views: 535

Answers (1)

Chuck Walbourn
Chuck Walbourn

Reputation: 41057

In short: don't use auto_ptr. It's basically broken. Use std::unique_ptr instead.

The way you are using auto_ptr is also really odd:

void CommandLoader::RegisterCommand(std::auto_ptr<ILoadableCommand> cmd)

This means every time you call this function, it makes a new auto_ptr which takes ownership of your buffer. You then give ownership of it to a shared_ptr.

This sounds like a case where you should really be giving the function a raw pointer, or at a minimum taking a reference:

void CommandLoader::RegisterCommand(std::unique_ptr<ILoadableCommand>& cmd)

This MSDN Magazine article covers this as well.

Upvotes: 1

Related Questions