gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:28:13 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com