简体   繁体   中英

Initialize a vector properly

struct the_raw_data {
    double data;
    double other;
};

int testingReadFunctionsout() {
    std::vector<the_raw_data> &thevector;  /*Here is where the initialization needs to happen*/ 
    return 0;
}

I am getting the following error:

main.cpp: In function ‘std::vector<the_raw_data>& readDataFromFileOut(std::__cxx11::string)’:
main.cpp:108:29: error: ‘v’ declared as reference but not initialized
  std::vector<the_raw_data>& v;

The error is self-explanatory:

'v' declared as reference but not initialized

You have declared a variable v that is a reference , but it does not reference anything:

std::vector<the_raw_data> &thevector; // what is thevector pointing at? NOTHING!

You can't have uninitialized references in C++. A reference is just an alias for another object, so you have to initialize it to point at something (in practical terms, think of a reference as being like a pointer that can never be NULL, because that is how most compilers actually implement it), eg:

std::vector<the_raw_data> &thevector = SomeOtherObject; 

Where SomeOtherObject is another std::vector<the_raw_data> object elsewhere in memory.

If you want v to be an actual std::vector<the_raw_data> object of its own, just get rid of the & in the variable declaration:

std::vector<the_raw_data> thevector;

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