Returning auto_ptr has different results on diferent gcc versions

69 views Asked by At

I have the following test code that I'm trying to run on QNX 6.5.0SP1 using gcc 4.4.2:

// auto_ptr::operator= example
#include <iostream>
#include <cstdio>
#include <memory>

std::auto_ptr<std::string> source(void)
{
  return std::auto_ptr<std::string>(new std::string("Hello World!\n"));
}

void sink(std::auto_ptr<std::string> arg)
{

}

int main () {
  std::auto_ptr<std::string> ap1 = source();// = ( new std::string("Hello World!\n"));
  std::auto_ptr<std::string> ap2 = source();
  std::printf("AP1 = %08d\nAP2 = %08d\n\n",ap1.get(), ap2.get());

   ap1 = source();
   std::printf("AP1 = %08d\nAP2 = %08d\n\n",ap1.get(), ap2.get());


  ap2 = ap1;
  std::printf("AP1 = %08d\nAP2 = %08d\n\n",ap1.get(), ap2.get());

  sink(ap2);
  std::printf("AP1 = %08d\nAP2 = %08d\n\n",ap1.get(), ap2.get());

  return 0;
}

When compiling I get the following error:

helloworld_app.cpp:28: error: no match for 'operator=' in 'ap1 = source()()'
note: candidates are:
std::auto_ptr<_Ty>& std::auto_ptr<_Ty>::operator=(std::auto_ptr<_Other>&) [with _Other = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Ty = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]
std::auto_ptr<_Ty>& std::auto_ptr<_Ty>::operator=(std::auto_ptr<_Ty>&) [with _Ty = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]
std::auto_ptr<_Ty>& std::auto_ptr<_Ty>::operator=(std::auto_ptr_ref<_Ty>&) [with _Ty = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]

I've tried running this code successfully via cygwin on my local machine using gcc 5.4.0 and also on http://cpp.sh/ which uses gcc 4.9.2. Is there a difference in the versions of gcc that prevents auto_ptr assignment from a function's return value vs another local auto_ptr? Any insight would be helpful.

I've seen the following 2 questions and read Herb Stutters post on auto_ptrs, and feel like I understood what they were saying about copies not being equal, but was confused as to why it seemingly behaves differently on different versions of gcc.

http://www.gotw.ca/publications/using_auto_ptr_effectively.htm

Is returning auto_ptr from functions wrong/error-prone?

How do you assign a returned auto_ptr?

0

There are 0 answers