按值返回STL容器会破坏堆... [英] Returning STL containers by value corrupts heap...
问题描述
当尝试返回类型为
的对象时
std :: list< MyClass>
>
来自我的函数,我得到一个损坏的堆。
(我使用MSVC ++ 7.0运行时堆检查工具检查)
基本上,我是创建本地对象
std :: list< MyClass> myObj;
填好数据后,最后我做了一个
返回myObj;
和进程暂停,InvalidPointerInHeap运行时异常
(基本上是一个损坏的堆)。
我觉得return语句必须调用std :: list副本
构造函数,必须执行容器的深层复制,
然后必须删除本地容器。
更不用说,myClass还有一个成员,另一个stl列表。
std :: list< myOtherClass> myMemberList;
(我在内部的析构函数中得到了堆异常错误消息
有没有其他人遇到类似STL的问题,或者这是预期的b / b
行为,还是我在其他地方做错了什么?
Sachin Garg [印度]
http://sachingarg.go.to >
推荐答案
" Sachin Garg" < SC ***** @ gmail.com>在消息中写道
新闻:b3 ************************* @ posting.google.co m ...
"Sachin Garg" <sc*****@gmail.com> wrote in message
news:b3*************************@posting.google.co m...
当我尝试从我的函数返回类型为
std :: list< MyClass>
的对象时,我得到了一个损坏的堆。
When trying to return objects of type
std::list<MyClass>
from my function, I get a corrupt heap.
我首先要仔细查看MyClass复制构造函数。
I would start by looking carefully at the MyClass copy constructor.
Sachin Garg在新闻中写道: b3*************************@posting.google.co m
comp.lang.c ++中的
:
Sachin Garg wrote in news:b3*************************@posting.google.co m
in comp.lang.c++:
当试图返回类型为
的对象时
std :: list< MyClass>
从我的功能,我得到一个腐败的堆。
(我检查使用MSVC ++ 7.0运行时堆检查工具)
Hi,
When trying to return objects of type
std::list<MyClass>
from my function, I get a corrupt heap.
(I checked using MSVC++ 7.0 runtime heap check facility)
您需要制作一个展示的测试程序问题,
然后在这里发布:
有几种可能性:
- 你的MyClass ;对象没有正确的复制构造函数
和赋值运算符。
- 在调用之前你已经损坏了堆
你的功能。
- ...
- 这是一个编译错误。 (这非常罕见,但它确实发生了。)
一个测试用例:
#include< iostream>
#include< list>
#include< cassert>
struct object
{
int i;
object(int ii):i(ii){}
};
std :: list<对象> f()
{
std :: list<对象> r;
for(int i = 0; i< 100; ++ i)
{
r.push_back(i);
}
返回r;
}
int main()
{
std :: list<对象> r = f();
std :: list< object> :: iterator
ptr = r.begin(),
lim = r.end()
;
for(int i = 0; i< 100; ++ i,++ ptr)
{
assert(ptr-> i == i);
}
std :: cout<< Ok \ n;
}
用VC ++ 7.1编译并运行良好。
注意那个对象没有用户定义的复制ctor或赋值
运算符,编译器生成的那些在这种情况下可以作为对象
不包含任何*资源* (新的'对象',文件等)。
HTH。
Rob。
-
http://www.victim-prime.dsl .pipex.com /
文章< b3 ********************* ****@posting.google.com> ,
sc*****@gmail.com (Sachin Garg)写道:
In article <b3*************************@posting.google.com> ,
sc*****@gmail.com (Sachin Garg) wrote:
当我尝试从我的函数返回类型为
std :: list< MyClass>
的对象时,我得到了一个腐败的堆。
(我使用MSVC ++ 7.0运行时堆检查工具检查)
基本上,我正在创建一个本地对象
std :: list< MyClass的> myObj;
填满数据后,最后我做了一个
返回myObj;
并且进程因InvalidPointerInHeap运行时异常而停止
(基本上是一个损坏的堆)。
我觉得return语句必须调用std :: list copy
构造函数,它必须执行一个深层复制的容器,
然后它必须删除本地容器。
更不用说,myClass还有一个成员,另一个stl列表。
std ::列表< myOtherClass> myMemberList;
(我在内部strd:list的析构函数中收到了堆异常错误消息)
是否有其他人遇到类似STL的问题,或者这是预期的行为,还是我在其他地方做错了什么?
Sachin Garg [印度]
http://sachingarg.go.to
最有可能MyClass的副本无效构造函数导致你看到的
症状。
-Howard
Most likely MyClass has an invalid copy constructor which is causing the
symptoms you''re seeing.
-Howard
这篇关于按值返回STL容器会破坏堆...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!