Update: Edited code example to use AutoA for the workaround (which was the original intention). Realized this after seeing rlbond's answer.
I am trying to incorporate the usage of auto_ptr
in my code based on recommendations from this thread:
However, I am receiving some unexpected compile errors when compiling with Visual Studio 6.0. It has a problem when dealing with assignments/copies of a std::auto_ptr
of a derived type to a std::auto_ptr
of the base type. Is this an issue specific to my compiler?
I know there's a strong recommendation to use Boost, but on my project it is not an option. If I still want to use auto_ptr
, am I forced to use the workaround of calling std::auto_ptr::release()
? From what I have encountered so far, this issue results in a compiler error, so it's easy enough to catch. However, could adopting the convention of calling release to assign to a 'auto_ptr' of base type throughout expose me to any maintenance issues? Especially if built with a different compiler (assuming other compilers don't have this issue).
If the release()
workaround is not good due to my circumstances, should I fall back on using a different convention for describing transfer of ownership?
The following is an example illustrating the problem.
#include "stdafx.h"
#include <memory>
struct A
{
int x;
};
struct B : public A
{
int y;
};
typedef std::auto_ptr<A> AutoA;
typedef std::auto_ptr<B> AutoB;
void sink(AutoA a)
{
//Some Code....
}
int main(int argc, char* argv[])
{
//Raws to auto ptr
AutoA a_raw_to_a_auto(new A());
AutoB b_raw_to_b_auto(new B());
AutoA b_raw_to_a_auto(new B());
//autos to same type autos
AutoA a_auto_to_a_auto(a_raw_to_a_auto);
AutoB b_auto_to_b_auto(b_raw_to_b_auto);
//raw derive to auto base
AutoB b_auto(new B());
//auto derive to auto base
AutoA b_auto_to_a_auto(b_auto); //fails to compile
//workaround to avoid compile error.
AutoB b_workaround(new B());
AutoA b_auto_to_a_auto_workaround(b_workaround.release());
sink(a_raw_to_a_auto);
sink(b_raw_to_b_auto); //fails to compile
return 0;
}
Compile Error:
Compiling...
Sandbox.cpp
C:\Program Files\Microsoft Visual Studio\MyProjects\Sandbox\Sandbox.cpp(40) : error C2664: '__thiscall std::auto_ptr<struct A>::std::auto_ptr<struct A>(struct A *)' : cannot convert parameter 1 from 'class std::auto_ptr<struct B>' to 'struct A *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
C:\Program Files\Microsoft Visual Studio\MyProjects\Sandbox\Sandbox.cpp(47) : error C2664: 'sink' : cannot convert parameter 1 from 'class std::auto_ptr<struct B>' to 'class std::auto_ptr<struct A>'
No constructor could take the source type, or constructor overload resolution was ambiguous
Error executing cl.exe.
Sandbox.exe - 2 error(s), 0 warning(s)