The following code does not compile on Visual C++ 2008 nor 2010:
#include <memory>
struct A {};
std::auto_ptr<A> foo() { return std::auto_ptr<A>(new A); }
const std::auto_ptr<A> bar() { return std::auto_ptr<A>(new A); }
int main()
{
const std::auto_ptr<A> & a = foo(); // most important const
const std::auto_ptr<A> & b = bar(); // error C2558:
// class 'std::auto_ptr<_Ty>' :
// no copy constructor available or copy
// constructor is declared 'explicit'
bar(); // No error?
}
I expected the "most important const" to apply to the variable "b", and yet, it does not compile, and for some reason, the compiler asks for a copy constructor (which surprises me as there should be no copy involved here). The standalone call to bar()
works fine, which means, I guess, it is really the initialization of b
that is the problem.
Is this a compiler bug, or a genuine compilation error described in the standard?
(perhaps it was forbidden in C++98 and authorized in C++11?)
Note: It does compile on Visual C++ 2012, gcc 4.6, and on Solaris CC (of all compilers...), but not gcc 3.4, nor XL C)
auto_ptr
, if your intention is to transfer ownership to the caller. – Louisalouisburgauto_ptr
is fine because there's a whole lot ofauto_ptr_ref
trickery specifically designed to make this sort of thing work. – Mercurializeconst std::auto_ptr
, but this is beside the point. – Ironystd::auto_ptr
is fine, the bigger question is why he's using a deprecated template to begin with.stdL::unique_ptr
should be used here. – Johannisbergerthe bigger question is why he's using a deprecated template to begin with. stdL::unique_ptr should be used here
: Because some compilers are still not C++11-enabled, perhaps?... :-) – Ironyunique_ptr
instd
.auto_ptr
is at least standardized in the version of C++ supported by all those compilers. – MercurializeHe has C++11 tagged, which would seem to indicate he can utilize the newer C++ features
: Not really: 1. Your observation is wrong because I added both the C++98 and C++11 tags because (and thus after) your initial comment... :-) ... 2. Your deduction is wrong because when you are cross-compiling (which I obviously am), you must use the common subset among the different compilers, not the features specific to two compilers among seven... Good try, anyway... :-) – Irony