简体   繁体   English

如何在 c++ 中设置指针向量 = 到 nullptr?

[英]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; (帐户是一个类),所以我有一个指针向量,我知道制作指针时的最佳做法是用某些东西初始化它或确保将其分配给 nullptr,但是当我执行std::vector<std::unique_ptr<Account>> openedAccounts = nullptr; or std::vector<std::unique_ptr<Account>> openedAccounts = std::vector<nullptr>;std::vector<std::unique_ptr<Account>> openedAccounts = std::vector<nullptr>; it doesn't work, so how would I set the openedAccounts to a nullptr ?它不起作用,那么我将如何将openedAccounts设置为nullptr

A default-constructed std::vector is empty, so you're all clear.默认构造的std::vector是空的,所以你很清楚。

Similarly, a default-constructed std::unique_ptr is null, so resizing your vector will work out-of-the-box as well.同样,默认构造的std::unique_ptr是 null,因此调整向量大小也可以开箱即用。

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.向量不是指针,也不是模拟指针的 class 即它不是智能指针也不是花哨的指针。 You cannot assign nullptr to a vector nor can you assign nullptr to it.您不能将nullptr分配给向量,也不能将nullptr分配给它。 There is no such thing as a null vector.没有 null 向量之类的东西。

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.无需进一步的步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM