其他分享
首页 > 其他分享> > c initializer_list和shared_ptr行为

c initializer_list和shared_ptr行为

作者:互联网

参见英文答案 > Double delete in initializer_list vs 2013                                    1个
我正在测试vs2013 c initializer_list.

可以编译下面的代码.
但是当我运行exe时崩溃了.

#include <memory>
#include <iostream>

class Base {};

class Derived : public Base {};

void DoSomething(std::initializer_list<std::shared_ptr<Base> > list)
{
}

int main()
{
  auto ip = std::make_shared<Derived>();

  std::cout << "use_count=" << ip.use_count() << std::endl;

  DoSomething({ip, std::make_shared<Derived>()}); // ng
  // DoSomething({ip, std::make_shared<Base>()}); // ok
  // DoSomething({std::make_shared<Derived>(), ip}); // ok

  std::cout << "use_count=" << ip.use_count() << std::endl;
}

编译.

C:\...>cl.exe /EHsc test.cpp
Microsoft(R) C/C++ Optimizing Compiler Version 18.00.21005.1 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

test.cpp
Microsoft (R) Incremental Linker Version 12.00.21005.1
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:test.exe
test.obj

C:\...>

我期待这样的输出.
g 4.8.2就是这样的.

c:\...>test.exe
use_count=1
use_count=1

但是,看起来像这样.

c:\...>test.exe
use_count=1
use_count=0 // or some random value like 3719232 and displayed crash dialog. 

并且,修改上面代码的一行,这很好用.

DoSomething({std::make_shared<Derived>(), ip});

这是vs2013 initializer_list的错误或正常行为吗?

解决方法:

Is this a bug or normal behavior of vs2013 initializer_list?

对两者都是. VS2013的std :: initializer_list实现是错误的;看到类似的问题Why first element is destroyed?Double delete in initializer_list vs 2013.

有人在2013年11月向Microsoft报告了其中一个问题:http://connect.microsoft.com/VisualStudio/feedback/details/807419/initializer-lists-leaking-memory

现在已在Spring Update中修复此问题:
Bugs Fixed in Visual Studio 2013 Update 2

标签:c,visual-studio-2013,initializer-list
来源: https://codeday.me/bug/20190929/1832130.html