[英]emplace_back and shared_ptr vector in VS2012
I have the following code: 我有以下代码:
#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);
}
And it always crashes on emplace_back()
. 而且它总是在
emplace_back()
上崩溃。 Yet it compiles fine, and I can't see any problem. 但是它编译良好,我看不到任何问题。 Why does it crash?
为什么会崩溃? Here is the exception thrown and the code line:
这是引发的异常和代码行:
Unhandled exception at 0x00FE2299 in ConsoleApplication2.exe: 0xC0000005: Access violation reading location 0x00000008.
at 在
vector.h - line 894: _VARIADIC_EXPAND_0X(_VECTOR_EMPLACE, , , , )
I am using VS2012 and have tried both with the November CTP and the default compiler. 我正在使用VS2012,并且已尝试使用11月CTP和默认编译器。
I cannot use VS2013 atm because of lack of boost support and other factors - is there a fix for MSVC11? 由于缺少增强支持和其他因素,我无法使用VS2013 atm-MSVC11是否有修复程序?
You need to create a vector<monkey>
that will be managed by the shared_ptr
. 您需要创建一个
vector<monkey>
,它将由shared_ptr
管理。
MonkeyContainer monkeyContainer;
After the above statement the shared_ptr
points to nullptr
( monkeyContainer.get() == nullptr
), and deferencing it to call emplace_back
results in the crash. 上面的语句之后,
shared_ptr
指向nullptr
( monkeyContainer.get() == nullptr
),然后将其emplace_back
以调用emplace_back
导致崩溃。 Change the above line to 将上面的行更改为
MonkeyContainer monkeyContainer = std::make_shared<std::vector<monkey>>();
You aren't initializing your MonkeyContainer
pointer. 您没有初始化
MonkeyContainer
指针。 It's pointing to NULL
when you try to emplace_back
. 当您尝试
emplace_back
时,它指向NULL
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.