简体   繁体   中英

How to set a vector of pointers = to nullptr in c++?

I have the following code

std::vector<std::unique_ptr<Account>> openedAccounts;

(Account is a class), so I have a vector of pointers and I know the best practice when making pointers is to initialize it with something or make sure its assigned to nullptr, however when i do std::vector<std::unique_ptr<Account>> openedAccounts = nullptr; or std::vector<std::unique_ptr<Account>> openedAccounts = std::vector<nullptr>; it doesn't work, so how would I set the openedAccounts to a nullptr ?

A default-constructed std::vector is empty, so you're all clear.

Similarly, a default-constructed std::unique_ptr is null, so resizing your vector will work out-of-the-box as well.

A vector isn't a pointer, nor is it a class that emulates a pointer ie it is not a smart pointer nor a fancy pointer. You cannot assign nullptr to a vector nor can you assign nullptr to it. There is no such thing as a null vector.

If you want to initialise the vector to be empty, you can use default initialisation as you did in your example (value initialisation also works). No further steps are necessary.

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