本文介绍了c ++ initializer_list和shared_ptr行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在测试vs2013 c ++ initializer_list。

I'm testing vs2013 c++ initializer_list.

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

The code below can be compiled.But crashes when i run 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就像这样。

I expected the output like this.g++4.8.2 works like this.

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

但是, / p>

However, looks like this.

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

然后,修改上面的代码中的一行,这很好。

And, Modifying one line of the code above, This works good.

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

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

Is this a bug or normal behavior of vs2013 initializer_list ?

推荐答案

是的。 VS2013的 std :: initializer_list 实现是错误的;请参阅类似的问题和

Someone reported one of those issues to Microsoft in November 2013: http://connect.microsoft.com/VisualStudio/feedback/details/807419/initializer-lists-leaking-memory

这在Spring更新中已修复:

This is now fixed in the Spring Update:Bugs Fixed in Visual Studio 2013 Update 2

这篇关于c ++ initializer_list和shared_ptr行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:11