Why doesn't auto_ptr construction work using = syntax

前端 未结 4 900
失恋的感觉
失恋的感觉 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:28

    It's the "explicit" keyword.

    template 
    struct foo
    {
      explicit foo(T const *)
      {
      }
    };
    
    
    template 
    struct bar
    {
      bar(T const *)
      {
      }
    };
    
    
    int main(int argc, char **argv)
    {
      int a;
      foo f = &a; // doesn't work
      bar b = &a; // works
    }
    

    The "explicit" keyword prevents the constructor from being used for implicit type conversions. Consider the following two function prototypes:

    void baz(foo const &);
    void quux(bar const &);
    

    With those definitions, try calling both functions with an int pointer:

    baz(&a);  // fails
    quux(&a); // succeeds
    

    In the case of quux, your int pointer was implicitly converted to a bar.

    EDIT: To expand on what other people commented, consider the following (rather silly) code:

    void bar(std::auto_ptr);
    
    
    int main(int argc, char **argv)
    {
      bar(new int()); // probably what you want.
    
      int a;
      bar(&a); // ouch. auto_ptr would try to delete a at the end of the
               // parameter's scope
    
      int * b = new int();
      bar(b);
      *b = 42; // more subtle version of the above.
    }
    

提交回复
热议问题