构造函数抛出的错误会rollback之前new的空间吗
构造函数抛出的异常会rollback之前new的空间吗?
此问题源自http://weibo.com/1915548291/z93t7a2U4
本人认为如果第二次new抛出异常的话,第一个new出来的内存会泄漏。并做实验如下:
用valgrind测试结果:
有没有人有其他意见的??
------解决方案--------------------
这个肯定会泄露。
此问题源自http://weibo.com/1915548291/z93t7a2U4
本人认为如果第二次new抛出异常的话,第一个new出来的内存会泄漏。并做实验如下:
class A
{
public :
A()
{
first = new char[10];
throw int(5);
}
~A()
{
delete [] first;
}
private:
char * first;
char * second;
};
int main()
{
try{
A a;
}
catch(int x){}
return 0;
}
用valgrind测试结果:
==2815== Memcheck, a memory error detector
==2815== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==2815== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==2815== Command: ./newmem
==2815==
==2815==
==2815== HEAP SUMMARY:
==2815== in use at exit: 10 bytes in 1 blocks
==2815== total heap usage: 2 allocs, 1 frees, 110 bytes allocated
==2815==
==2815== 10 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2815== at 0x40277B2: operator new[](unsigned int) (vg_replace_malloc.c:357)
==2815== by 0x80486BF: A::A() (newmem.cpp:8)
==2815== by 0x8048678: main (newmem.cpp:32)
==2815==
==2815== LEAK SUMMARY:
==2815== definitely lost: 10 bytes in 1 blocks
==2815== indirectly lost: 0 bytes in 0 blocks
==2815== possibly lost: 0 bytes in 0 blocks
==2815== still reachable: 0 bytes in 0 blocks
==2815== suppressed: 0 bytes in 0 blocks
==2815==
==2815== For counts of detected and suppressed errors, rerun with: -v
==2815== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 17 from 6)
有没有人有其他意见的??
------解决方案--------------------
这个肯定会泄露。