Home > OS >  How to set a vector of pointers = to nullptr in c ?
How to set a vector of pointers = to nullptr in c ?

Time:12-07

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?

CodePudding user response:

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.

CodePudding user response:

A vector isn't a pointer, nor is it a class that emulates a pointer i.e. 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.

  • Related