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) { }
It’s the ‘explicit’ keyword.
The ‘explicit’ keyword prevents the constructor from being used for implicit type conversions. Consider the following two function prototypes:
With those definitions, try calling both functions with an int pointer:
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: