C ++ - Is there an implicit cast here from Fred * to auto_ptr <Fred>?

I saw the following code,

#include <new> #include <memory> using namespace std; class Fred; // Forward declaration typedef auto_ptr<Fred> FredPtr; class Fred { public: static FredPtr create(int i) { return new Fred(i); // Is there an implicit casting here? If not, how can we return // a Fred* with return value as FredPtr? } private: Fred(int i=10) : i_(i) { } Fred(const Fred& x) : i_(x.i_) { } int i_; }; 

Please review the question mentioned in the create function.

thanks

// Updated based on comments

Yes, the code cannot pass VC8.0 error C2664: 'std :: auto_ptr <_Ty> :: auto_ptr (std :: auto_ptr <_Ty> &) throw ()': cannot convert parameter 1 from 'Fred *' to ' std :: auto_ptr <_Ty> &

The code was copied from the C ++ FAQ 12.15.

However, after making the following changes

 replace return new Fred(i); with return auto_ptr<Fred>(new Fred(i)); 

This code can be passed by the VC8.0 compiler. But I'm not sure if this fix is ​​correct.

+4
source share
3 answers

std::auto_ptr has a constructor that takes a source pointer as its argument, but this constructor is explicit and cannot be used as a conversion constructor.

This code will not compile.

+6
source

No, there is no such implicit conversion. Turns out this is actually a good thing. For example, consider this code:

 void MyFunction(const std::auto_ptr<Fred>& myFred) { /* ... do something to Fred. */ } int main() { Fred* f = new Fred; MyFunction(f); // Not legal, but assume it is. f->doSomething(); } 

Here, if you can pass the raw pointer to Fred to MyFunction, then when this function returns and the temporary auto_ptr object is cleared, the memory you allocated in main () will be restored, and the call f-> doSomething () will probably will call segfault. Creating an explicit auto_ptr constructor is a defense against this; you don’t want to accidentally acquire exclusive ownership of a resource when someone else believes that they already have that access.

+3
source

The fixed version of the code ( return std::auto_ptr<Fred>(new Fred()) ) is correct and valid C ++. However, I'm not sure if the create() function buys you that creating std::auto_ptr<T> should be within the skill set of any C ++ programmer. Similarly, I do not understand that typedef ing std::auto_ptr<Fred> to FredPtr buys you, besides having to look for what FredPtr really is.

0
source

Source: https://habr.com/ru/post/1333958/


All Articles