为什么不使用auto_ptr构造工作using =语法 [英] Why doesn't auto_ptr construction work using = syntax
问题描述
我遇到了一个编译器错误,对我没有什么意义:
#include< memory>
using namespace std;
auto_ptr< Table> table = db-> query(select * from t);
错误:从'Table *'转换为非标量类型'std :: auto_ptr&表>请求
但是,以下行会起作用:
auto_ptr< Table> table(db-> query(select * from t));
这个定义的构造函数是什么,阻止它像我预期的那样工作?我认为初始化的声明使用了构造函数。
这是我的 auto_ptr
的构造函数
explicit
auto_ptr(element_type * __p = 0)throw():_M_ptr(__ p){}
这是显式关键字。
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; // does not work
bar< int> b =& a; // works
}
explicit关键字阻止构造函数用于隐式类型转换。考虑下面两个函数原型:
void baz(foo< int> const&
void quux(bar< int> const&);
使用这些定义,尝试使用int指针调用两个函数:
baz(& a); // failed
quux(& a); //成功
在quux的情况下,int指针隐式转换为bar。 p>
EDIT:要扩展其他人评论过的内容,请考虑以下(相当蠢)代码:
void bar(std :: auto_ptr< int>);
int main(int argc,char ** argv)
{
bar(new int()); //可能你想要什么。
int a;
bar(& a); //噢。 auto_ptr将尝试在
//参数的作用域的末尾删除一个
int * b = new int();
bar(b);
* b = 42; //更微妙的版本的上面。
}
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.
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.
}
这篇关于为什么不使用auto_ptr构造工作using =语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!