How do I return an auto_ptr of a base class using an auto_ptr of a derived class?

StackOverflow https://stackoverflow.com/questions/23691185

  •  29-07-2023
  •  | 
  •  

문제

I am working through some older code that must return an std::auto_ptr, with which I have relatively little experience. I have run into a situation like this:

// I need to populate this function
std::auto_ptr<Base> Func()
{
  std::auto_ptr<Derived> derivedPtr = new Derived;

  // now I want to return

  return derivedPtr; // error: conversion from std::auto_ptr<Derived> to std::auto_ptr<Base> is ambiguous
}

Do I need to release auto_ptr first? The really overly explicit way would be something like return static_cast<Base>(derivedPtr.release()) but I suspect this isn't necessary.

도움이 되었습니까?

해결책

You can use...

return std::auto_ptr<Base>(derivedPtr);   // explicitly use constructor

...or...

return derivedPtr.operator std::auto_ptr<Base>();  // use cast/conversion operator

(The reason you can't just return derivedPtr is that the above are ambiguous candidates).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top