簡體   English   中英

VS2012中的emplace_back和shared_ptr向量

[英]emplace_back and shared_ptr vector in VS2012

我有以下代碼:

#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,並且已嘗試使用11月CTP和默認編譯器。

由於缺少增強支持和其他因素,我無法使用VS2013 atm-MSVC11是否有修復程序?

您需要創建一個vector<monkey> ,它將由shared_ptr管理。

MonkeyContainer monkeyContainer;

上面的語句之后, shared_ptr指向nullptrmonkeyContainer.get() == nullptr ),然后將其emplace_back以調用emplace_back導致崩潰。 將上面的行更改為

MonkeyContainer monkeyContainer = std::make_shared<std::vector<monkey>>();

您沒有初始化MonkeyContainer指針。 當您嘗試emplace_back時,它指向NULL

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM