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
  •  | 
  •  

Frage

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.

War es hilfreich?

Lösung

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).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top