c – 为什么auto_ptr构造不能使用=语法
发布时间:2020-12-16 05:48:59 所属栏目:百科 来源:网络整理
导读:我遇到了一个对我没有什么意义的编译器错误: #include memoryusing namespace std;auto_ptrTable table = db-query("select * from t"); 错误:从’Table *’转换为非标量类型’std :: auto_ptr表”要求 但是,以下行可以正常工作: auto_ptrTable table(db-
我遇到了一个对我没有什么意义的编译器错误:
#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的构造函数(从SGI STL): 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; // doesn't work bar<int> b = &a; // works } “显式”关键字可防止构造函数用于隐式类型转换.考虑以下两个函数原型: void baz(foo<int> const &); void quux(bar<int> const &); 使用这些定义,尝试使用int指针调用这两个函数: baz(&a); // fails quux(&a); // succeeds 在quux的情况下,您的int指针被隐式转换为一个条. 编辑:要扩展其他人评论的内容,请考虑以下(相当愚蠢)的代码: 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. } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |