简体   繁体   中英

c++ std::vector "this" was "nullptr"

for some reason I can not use the vector _vec in datacenter.cpp. It says " this " was "nullptr"

please help, thanks <3

datacenter.h

#pragma once
#include <iostream>
#include <vector>

class datacenter
{
public:
    datacenter();
    ~datacenter();

    void get_elements();

    std::vector<float> _vec;
};

datacenter.cpp

#include "datacenter.h"

datacenter::datacenter(){}

void datacenter::get_elements()
{
if (_vec.empty()) { //<---- the error appears here
    std::cout << "empty" << std::endl;
    }
}

datacenter::~datacenter(){}

main.cpp

#include <iostream>
#include <vector>
#include "datacenter.h"

class datacenter;

int main()
{
std::unique_ptr<datacenter> dc;
dc->get_elements();
}

The trouble comes from:

std::unique_ptr<datacenter> dc;

This does not create an instance of datacenter , but only a (null) (smart) pointer to it. You need to create an instance with:

auto dc = std::make_unique<datacenter>();

See also

A std::unique_ptr is a container of an object, the object contained must be initialized as if it were a non-smart pointer, it's not automatically constructed with black magic.

What you are doing is roughly equivalent to

datacenter* dc = nullptr;
dc->get_elements();

You need to istantiate the object first:

auto dc = std::make_unique<datacenter>();

Mind that you are lucky you were using a std::unique_ptr because a non initialized variable would have contained a garbage value (instead that nullptr ) making debugging harder in a real life example.

You unique pointer is not initialized and its content is null. You should initialize it this way :

std::unique_ptr<datacenter> dc = std::unique_ptr<datacenter>(new datacenter());

http://coliru.stacked-crooked.com/a/b54fa5fc05396e65

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