Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

c++ - Why doesn't auto_ptr construction work using = syntax

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

#include <memory>
using namespace std;

auto_ptr<Table> table = db->query("select * from t");

error: conversion from 'Table*' to non-scalar type 'std::auto_ptr< Table>' requested

However, the following line does work:

auto_ptr<Table> table(db->query("select * from t"));

What is it about this definiton of the constructor that prevents it from working as I expect? I thought that initialized declarations used the constructors.

Here's my auto_ptr's constructor (from the SGI STL):

explicit
auto_ptr(element_type* __p = 0) throw() : _M_ptr(__p) { }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's the "explicit" keyword.

template <typename T>
struct foo
{
  explicit foo(T const *)
  {
  }
};


template <typename T>
struct bar
{
  bar(T const *)
  {
  }
};


int main(int argc, char **argv)
{
  int a;
  foo<int> f = &a; // doesn't work
  bar<int> 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<int> const &);
void quux(bar<int> 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>);


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...