简体   繁体   中英

C++ vector deallocation on constructor

Sorry I don't have time to code this out, I hope my explanation is thorough enough. One of my classes has a vector as a private member variable, and its size is declared in its constructor.

Now, I've discovered from debugging that while the vector does get its size allocated in the constructor, it loses it all when the constructor returns (as if though its memory allocation is only in the scope of the constructor, even though the vector is one of its member variables. It goes back to being an empty vector) I need my vector to retain its size past the execution of the constructor, and was wondering what I could do to fix this issue, as I initialize its elements with strings in one of my other functions.

Appending content from comment

std::vector< std::vector< std::string > > routeInfo(
    routeNum, std::vector< std::string >( 2 ) );

This is the vector's declaration in my constructor, routeNum is a variable which is initialized earlier in the constructor (initialized correctly, thats not the issue).

I must assume from you're code that you are not aware how to initialize member variables in c++. This is the correct way:

class Myclass
{
// the declaration of the variable:
std::vector< std::vector< std::string > > routeInfo;

// declaration of the constructor:
Myclass(int routeNum);
};

// definition of the constructor
Myclass::Myclass(int routeNum)
  : routeInfo(routeNum, std::vector< std::string >( 2 ))
{
  // some other code
}

If you simply write:

Myclass::Myclass(int routeNum)
{
std::vector< std::vector< std::string > > routeInfo(
    routeNum, std::vector< std::string >( 2 ) );
}

This will create ANOTHER routeInfo variable witch hides the original, in the constructor. To reach the member variable you'd have to write this->routeInfo instead of routeInfo and that will be still zero length.

It sounds to me like you're somehow assigning over the vector somewhere in your code (or perhaps over the entire object with another where you didn't specify the size of the vector).

The vector itself should not change size if you specified the size correctly. Though one thing to check:

Did you specify the maximum capacity, or did you specify the current capacity using reserve? If you call reserve, the vector should expand to the space you allot and stay there until you exceed it or explicitly request a change in size.

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