Ender
Ender

Reputation: 1778

How to declare unique_ptr of vector?

I am trying to declare a global vector of MyClass using unique_ptr. My compiler is 4.8.4.

glo.h

extern std::unique_ptr<std::vector<MyClass>> gl_vec;

glo.cpp

std::unique_ptr<std::vector<MyClass>> gl_vec;

And in the file where I initialize and use it for the first time in a different *.cpp file:

#include "glo.h"

// within function 
{
    gl_vec = std::unique_ptr<std::vector<MyClass>> ();

    cout << "gl_vec size = " << (*gl_vec).size() << endl; // crashes here
}

Things keep crashing when I use the pointer. Anyone see what I'm doing wrong?

Upvotes: 5

Views: 12191

Answers (3)

tsandy
tsandy

Reputation: 931

A unique_ptr's pointer value is null unless you initialize or assign a valid pointer value.

gl_vec = std::unique_ptr<std::vector<MyClass>>(new std::vector<MyClass>());

Upvotes: 8

fukanchik
fukanchik

Reputation: 2865

constexpr unique_ptr(); - Constructs a std::unique_ptr that owns nothing.

gl_vec = std::unique_ptr<std::vector<MyClass>> ();

Constructs a std::unique_ptr that owns nothing.

(*gl_vec).size()

std::unique_ptr::operator* - operator* and operator-> provide access to the object owned by *this.

*gl_vec - provides access to nothing. Hence - crash.

What you really want to do is:

gl_vec = std::make_unique<std::vector<MyClass>> ();

Upvotes: 3

Anton Savin
Anton Savin

Reputation: 41341

You aren't allocating memory for the underlying vector.

Instead of

gl_vec = std::unique_ptr<std::vector<MyClass>> ();

do this:

gl_vec = std::make_unique<std::vector<MyClass>>();

Or if C++14 is not available

gl_vec.reset(new std::vector<MyClass>());

Upvotes: 5

Related Questions