JosiP
JosiP

Reputation: 3079

stl vector of pointers initilaziation

In some code, which some years ago could be compiled, now im having errors, here is the line:

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

it seems, that someone want to initalize a vector of size aCount (type long), and each pointer want to initialize to null. Looking at stl documetation, in this case, someone is trying to use fill constructor:

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

Constructs a container with n elements. Each element is a copy of val

My compiler is giving me errors:

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

So, to fix it shall i just remove NULL, and use default vector constructor, or is there any other option, to initialize each pointer in that vector to NULL ?

regards J.

Upvotes: 0

Views: 703

Answers (1)

dunc123
dunc123

Reputation: 2713

The problem is that NULL is simply 0 which isn't interpreted as a pointer. You'll need to cast it to a aRequest*.

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

You could also use nullptr in C++11 or simply nothing as suggested by commenters.

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

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

Upvotes: 1

Related Questions