我有以下代码:
#include <vector>
#include <algorithm>
#include <memory>
struct monkey
{
int mA, mB;
monkey(int a, int b) : mA(a), mB(b)
{
}
};
typedef std::shared_ptr<std::vector<monkey>> MonkeyContainer;
int main()
{
MonkeyContainer monkeyContainer;
monkeyContainer->emplace_back(1, 2);
}
它总是在 emplace_back()
上崩溃。然而它编译得很好,我看不出任何问题。为什么会崩溃?
这是抛出的异常和代码行:
Unhandled exception at 0x00FE2299 in ConsoleApplication2.exe: 0xC0000005: Access violation reading location 0x00000008.
在
vector.h - line 894: _VARIADIC_EXPAND_0X(_VECTOR_EMPLACE, , , , )
我使用的是 VS2012,并尝试使用 November CTP 和默认编译器。
由于缺乏增强支持和其他因素,我无法使用 VS2013 atm - 是否有针对 MSVC11 的修复程序?
最佳答案
您需要创建一个 vector<monkey>
将由 shared_ptr
管理.
MonkeyContainer monkeyContainer;
在上面的语句之后shared_ptr
指向 nullptr
( monkeyContainer.get() == nullptr
),并将其引用为调用 emplace_back
结果导致崩溃。将上面一行改为
MonkeyContainer monkeyContainer = std::make_shared<std::vector<monkey>>();
关于c++ - VS2012 中的 emplace_back 和 shared_ptr vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19235308/