STL里面的vector在删除一段元素后都会调用destory()函数,destroy函数会调用析构函数,那要是内置类型的元素怎么办?

一招半式闯江湖 2012-09-28 03:07:31
STL里面的vector在删除一段元素后都会调用destory()函数,destroy函数会调用析构函数,那要是内置类型的元素怎么办?哪来的析构函数?
...全文
321 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
typedef int myint;

void destruct2 (myint * item)
{
item->~myint();
}
不懂你这段代码有啥用?
stereoMatching 2012-09-28
  • 打赏
  • 举报
回复
答案是完全没有问题
mingliang1212已经回复了
因为destroy是个template function

不行

void destruct1 (int * item)
{
item->~int();
}


可行

typedef int myint;

void destruct2 (myint * item)
{
item->~myint();
}


语法上的一些陷阱
  • 打赏
  • 举报
回复
iterator erase(iterator position) {
if (position + 1 != end())
copy(position + 1, finish, position);
--finish;
destroy(finish);
return position;
}
这里的destory(finish)怎么办?如果finish是个int *p那么哪来的p->~int();
iamnobody 2012-09-28
  • 打赏
  • 举报
回复
5.2.4 Pseudo destructor call [expr.pseudo]
1 The use of a pseudo-destructor-name after a dot . or arrow -> operator represents the destructor for the
non-class type named by type-name. The result shall only be used as the operand for the function call operator
(), and the result of such a call has type void. The only effect is the evaluation of the postfixexpression
before the dot or arrow.
2 The left hand side of the dot operator shall be of scalar type. The left hand side of the arrow operator shall
be of pointer to scalar type. This scalar type is the object type. The type designated by the pseudodestructor-
name shall be the same as the object type. Furthermore, the two type-names in a pseudodestructor-
name of the form
::opt nested-name-specifieropt type-name :: ˜ type-name
shall designate the same scalar type. The cv-unqualified versions of the object type and of the type designated
by the pseudo-destructor-name shall be the same type.


另外destroy 不是标准函数.
stereoMatching 2012-09-28
  • 打赏
  • 举报
回复
假设你读的是侯老师的书好了(也就是SGI STL的源码)
destroy已经overload了,如果是内置类型的元素,会呼叫"什么都不做"的版本
至于如何判断那是不是内置类型的元素,则是透过一个叫做type_traits的技巧
是meta programming中一个很实用的工具

64,641

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧