c++ initializer_list and shared_ptr behavior(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
但是,看起来像这样.
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 initializer_list 的错误还是正常行为?
Is this a bug or normal behavior of vs2013 initializer_list?
是的.VS2013 的 std::initializer_list
实现有问题;看到类似的问题为什么第一个元素被销毁?和initializer_list 与 2013 年的双重删除.
Yes to both. VS2013's std::initializer_list
implementation is buggy; see similar questions Why first element is destroyed? and Double delete in initializer_list vs 2013.
有人在 2013 年 11 月向 Microsoft 报告了其中一个问题:http://connect.microsoft.com/VisualStudio/feedback/details/807419/initializer-lists-leaking-memory
Someone reported one of those issues to Microsoft in November 2013: http://connect.microsoft.com/VisualStudio/feedback/details/807419/initializer-lists-leaking-memory
此问题现已在 Spring 更新中修复:修复了错误在 Visual Studio 2013 更新 2
This is now fixed in the Spring Update: Bugs Fixed in Visual Studio 2013 Update 2
这篇关于c++ initializer_list 和 shared_ptr 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++ initializer_list 和 shared_ptr 行为


基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01