简体   繁体   中英

How to correctly initialize a vector of objects in C++?

I am fairly new to C++ and am trying to create a vector of an object and initialize its member, but there is this bit that I'm not sure if I'm doing correctly:

 vector<Card> cardStorage;
   for (int i = 0; i < 20; i++) {
         Card card;
         
         cardStorage.push_back(card);
     
     }

Basically that is a vector of 20 object of class Card, and push_back takes type Card &, which is pass by reference. Thus, I am not sure if doing this will yield a vector of 20 different Card objects, or all 20 members of the vector will point at one object, which is not what I want since I will need to traverse through this vector to manipulate the object data member (I also definitely don't want to create 20 object of class Card and push it into the vector, since that's obviously bad practice).

push_back on a vector makes a copy of the passed in argument, if the argument is an l-value (an object with a name). So cardStorage is guaranteed to have 20 distinct Card objects in it after the loop is executed, because each Card is copied into the vector .

You could consider using emplace_back to avoid unnecessarily copying the Card s into the vector , but you could also simply do:

vector<Card> cardStorage(20);

which achieves the same effect as the shown code.

That's fine. While push_back takes a const-reference (or an rvalue-reference in the overload), your vector holds objects of type Card . In this case you'll simply copy the temporary.

You could even avoid creating the temporary at all and call emplace_back() to create the new objects directly in the vector buffer, or if they're all supposed to be default-constructed, use .resize() or a constructor that takes the desired size.

Your example is correct. But it may be more effective. The most efficient way to init a vector in runtime will be the following (since C++17).

vector<Card> cardStorage;
// allocates memory for all the objects
cardStorage.reserve(20); 
for (int i = 0; i < 20; i++) {
    // constructs the object in-place and returns the reference to that object 
    // so that you you can do smth with card
    auto &card = cardStorage.emplace_back(/*Arguments if needed*/); 
}

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