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()
. 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.
I cannot use VS2013 atm because of lack of boost support and other factors - is there a fix for MSVC11?
You need to create a vector<monkey>
that will be managed by the 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. Change the above line to
MonkeyContainer monkeyContainer = std::make_shared<std::vector<monkey>>();