求 c++大神帮忙看下这段代码为啥不崩

2017-06-27 17:03:22 +08:00
 scinart
#include <vector>  
class Holder  
{  
    int* p;  
public:  
    Holder(int x) {
        p=new int();
        *p=x;
    }
    ~Holder() {
        delete p;
    }
};
int main(int argc, char *argv[])
{
    std::vector<Holder> v;
    v.reserve(3);
    v.emplace_back(1);
    v.emplace_back(2);
    v.emplace_back(3);
    v[1].~Holder();
    return 0;
}

应该崩是不是,但是我在 linux 上死活不崩,cpp.sh 上也正常运行。去 stackoverflow 问之前先看看 v 友有没有能解答的?

3450 次点击
所在节点    C
23 条回复
seancheer
2017-06-28 14:08:34 +08:00
@dayoushen emplace_back 是 c++ 11 的,和系统无关。。
xss
2017-06-28 14:32:58 +08:00
@gnaggnoyil 我理解错文档里面的意思了.
http://en.cppreference.com/w/cpp/container/vector/emplace_back
这个里面的 placemant-new 应该是'as is'的意思, 对象在哪里构造, vector 就放在那里构造的对象....
shibingsw
2017-06-28 22:32:45 +08:00
代码肯定有问题,double free 了,但是因为 double free 是未定义的,所以不一定会挂掉。
用 valgrind 也能清楚的看到多了一次 free:
```
==5561== Invalid free() / delete / delete[] / realloc()
==5561== at 0x4C2C64B: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5561== by 0x4009C7: Holder::~Holder() (in /vagrant/Work/waimai/inf_waf/j/build/a.out)
==5561== by 0x40161A: void std::_Destroy<Holder>(Holder*) (in /vagrant/Work/waimai/inf_waf/j/build/a.out)
==5561== by 0x401500: void std::_Destroy_aux<false>::__destroy<Holder*>(Holder*, Holder*) (in /vagrant/Work/waimai/inf_waf/j/build/a.out)
==5561== by 0x401187: void std::_Destroy<Holder*>(Holder*, Holder*) (in /vagrant/Work/waimai/inf_waf/j/build/a.out)
==5561== by 0x400CE4: void std::_Destroy<Holder*, Holder>(Holder*, Holder*, std::allocator<Holder>&) (in /vagrant/Work/waimai/inf_waf/j/build/a.out)
==5561== by 0x400A1C: std::vector<Holder, std::allocator<Holder> >::~vector() (in /vagrant/Work/waimai/inf_waf/j/build/a.out)
==5561== by 0x40092B: main (in /vagrant/Work/waimai/inf_waf/j/build/a.out)
==5561== Address 0x5a9fd30 is 0 bytes inside a block of size 4 free'd
==5561== at 0x4C2C64B: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5561== by 0x4009C7: Holder::~Holder() (in /vagrant/Work/waimai/inf_waf/j/build/a.out)
==5561== by 0x40091A: main (in /vagrant/Work/waimai/inf_waf/j/build/a.out)
==5561== Block was alloc'd at
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/371440

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX