assigning auto_ptrs  
Author Message
nhtim





PostPosted: Fri Jan 28 15:59:57 CST 2005 Top

Visual Studio C++ >> assigning auto_ptrs

When I compile the code below I get this warning:
warning C4239: nonstandard extension used : 'argument' : conversion from
'std::auto_ptr<_Ty>' to 'std::auto_ptr<_Ty> &' with
[ _Ty=int ] and [
_Ty=int ]

#include <memory>
using namespace std;
auto_ptr< int > f( )
{
auto_ptr< int > a( NULL );
return a;
}
int __cdecl main( )
{
auto_ptr< int > b;
b = f( ); // Warning?
return 0;
}
Why does the compiler NOT call operator auto_ptr_ref on the returned object
and then operator =( auto_ptr_ref ) on b?
What does the standard say about assigning a returned auto_ptr to another
auto_ptr?

Visual Studio44  
 
 
Igor





PostPosted: Fri Jan 28 15:59:57 CST 2005 Top

Visual Studio C++ >> assigning auto_ptrs

> When I compile the code below I get this warning:
> warning C4239: nonstandard extension used : 'argument' : conversion
> from 'std::auto_ptr<_Ty>' to 'std::auto_ptr<_Ty> &' with
> [ _Ty=int ] and [
> _Ty=int ]
>
> #include <memory>
> using namespace std;
> auto_ptr< int > f( )
> {
> auto_ptr< int > a( NULL );
> return a;
> }
> int __cdecl main( )
> {
> auto_ptr< int > b;
> b = f( ); // Warning?
> return 0;
> }
> Why does the compiler NOT call operator auto_ptr_ref on the returned
> object and then operator =( auto_ptr_ref ) on b?
> What does the standard say about assigning a returned auto_ptr to
> another auto_ptr?

The standard says that you are correct. However, VC compilers (all
versions I know of) implement a non-standard extension whereby a
temporary is allowed to bind to a non-const reference. Such a binding
ranks higher than user-defined conversion operator, that's why it ends
up being chosen. The end result in your case is the same, so you can
safely ignore this warning.

You can disable non-standard extensions using /Za switch (there's a
corresponding option somewhere in project settings), then the code will
behave as defined in the standard, via auto_ptr_ref conversion. Note
that it is next to impossible to do any Windows programming with /Za
turned on, since Platform SDK headers rely heavily on MS-specific
extensions.
--
With best wishes,
Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925