如何使用空指针初始化unique_ptr的向量? [英] How to initialize a vector of unique_ptr with null pointers?

查看:194
本文介绍了如何使用空指针初始化unique_ptr的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 nullptr s初始化 vector< unique< TNode>> 帖子中的方法过于复杂。我的情况很特殊,因为我只需要将其初始化为 nullptr 。我该如何实现?

I need to initialize a vector<unique<TNode>> with nullptrs. The method in this post is too complicated. My situation is special since I only need to initialize it as nullptr. How can I achieve it?

我知道我可以使用for循环来 push_back nullptr

I know I can use a for-loop to push_back a nullptr each time. Is there an elegant way?

BTW, make_unqiue 在我的编译器上不起作用。

BTW, make_unqiue does not work on my compiler.

#include <iostream>
#include <memory>
#include <vector>

using namespace std;

struct TNode {
    //char ch;
    bool isWord;
    vector<unique_ptr<TNode> > children;
    TNode(): isWord(false), children(26,nullptr) {}
};

int main()
{
    TNode rt;
    return 0;
}


推荐答案

std::vector<std::unique_ptr<int>> v (10);

它将创建一个向量为10的向量对象,所有对象均默认初始化(不制作任何副本)。 unique_ptr 的默认初始化不指向任何内容。

It will create a vector of 10 unique_ptr objects, all of which are default initialized (not making any copies). The default initialization for unique_ptr points to nothing.

请注意,这与以下内容完全不同:

Note this is quite different from this:

std::vector<std::unique_ptr<int>> v (10, nullptr);

试图用10个 unique_ptr副本复制矢量初始化为 nullptr 的c $ c>,由于无法复制 unique_ptr ,因此无法完成。

Which tries to initialize the vector with 10 copies of a unique_ptr that is initialized to nullptr, which cannot be done since unique_ptr can't be copied.

这篇关于如何使用空指针初始化unique_ptr的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆