c++ - 指针初始化的STL vector

标签 c++ stl

在一些几年前可以编译的代码中,现在我有错误,这是一行:

std::vector<aRequest*> requests(aCount, NULL);

似乎有人想要初始化一个大小为 aCount 的 vector (type long),并且每个指针都想初始化为 null。查看 STL 文档,在这种情况下,有人试图使用填充构造函数:

explicit vector (size_type n, const value_type& val = value_type(),
                 const allocator_type& alloc = allocator_type());

构造一个包含 n 个元素的容器。每个元素都是 val 的拷贝

我的编译器给我错误:

In file included from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/vector:65,
                 from server/ServerCreator.h:29,
                 from server/ServerApplication.h:31,
                 from server/ServerApplication.cpp:24:
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_vector.h: In member function âvoid std::vector<_Tp, _Alloc>::_M_initialize_dispatch(_Integer, _Integer, std::__true_type) [with _Integ er = long int, _Tp = ToolboxServer::aRequest*, _Alloc = std::allocator<ToolboxServer::aRequest*>]:
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_vector.h:303:   instantiated from âstd::vector<_Tp, _Alloc>::vector(_InputIterator, _InputIterator, const _Alloc&) [with _InputIterator = long int, _Tp = ToolboxServer::aRequest*, _Alloc = std::allocator<ToolboxServer::aRequest*>]
server/ServerApplication.cpp:1056:   instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_vector.h:991: error: invalid conversion from long int to ToolboxServer::aRequest*
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_vector.h:991: error:   initializing argument 2 of âvoid std::vector<_Tp, _Alloc>::_M_fill_initialize(size_t, const _Tp&) [with _Tp = ToolboxServer::aRequest*, _Alloc = std::allocator<ToolboxServer::aRequest*>]
make: *** [bin/Debian/x86/GCC4/2.6/Release/ServerApplication.o] Error 1

因此,要修复它,我应该删除 NULL,并使用默认 vector 构造函数,或者是否有任何其他选项,将该 vector 中的每个指针初始化为 NULL

问候 J.

最佳答案

问题是 NULL就是0这不被解释为指针。您需要将其转换为 aRequest* .

std::vector<aRequest*> requests(aCount, static_cast<aRequest*>(NULL));

你也可以使用 nullptr在 C++11 中,或者根本没有评论者建议的那样。

std::vector<aRequest*> requests(aCount, nullptr);

std::vector<aRequest*> requests(aCount);

关于c++ - 指针初始化的STL vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18310091/

相关文章:

c++ - 是否可以对使用 Boost Hana 的方法进行内省(introspection)?

C++ priority_queue size() 问题

android - 如何使用android ndk访问相机

c++ - 使用基于范围的 for 循环将对象 emplace_back 到 vector 中的正确方法是什么? C++

C++映射指针变量排序

html - 尝试使用正则表达式提取一段HTML代码

c++ - 橙色的 QPen?

c++ - const_cast<double*> 有效但 const_cast<int*> 无效

c++ - 为什么 std::set 没有 "contains"成员函数?

c++ - 基于堆栈缓冲区的STL分配器?