简体   繁体   中英

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() . 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>>();

You aren't initializing your MonkeyContainer pointer. It's pointing to NULL when you try to emplace_back .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM