Why doesn't auto_ptr construction work using = syntax

前端 未结 4 901
失恋的感觉
失恋的感觉 2020-12-16 20:04

I ran into a compiler error that didn\'t make much sense to me:

#include 
using namespace std;

auto_ptr table = db->query(\"se         
4条回答
  •  北海茫月
    2020-12-16 20:39

    The constructor is declared as explicit, which means that it won't be used for implicit type casting. Implicit conversion to auto_ptr could easily lead to undesirable situations since the auto_ptr is taking ownership of the pointer.

    For example, if auto_ptr would allow implicit conversion from a pointer and you accidentally passed a pointer to a method taking an auto_ptr the pointer would be silently converted to an auto_ptr and subsequently deleted when the function ends, even if that wasn't the intention. But by marking the constructor as explicit conversion can no longer happen silently and by calling the constructor you clearly express the intention of passing ownership to the auto_ptr, thus avoiding any potential confusion.

    void fun(std::auto_ptr foo) // Assume implicit conversion is allowed.
    {
        // do stuff with foo
    }
    
    Foo *foo = new Foo();
    
    f(foo); // Normally this isn't allowed.
    
    foo->bar(); // Oops
    

提交回复
热议问题