C ++ cannot initialize a pointer paired to NULL

I am compiling with g ++ 4.4.7 (and can't go further) and using the compiler switch -std=gnu++0x , which should allow the syntax of the third line.

 typedef std::vector<CI_RecordInfo_Pair> CI_RecordInfo_Vector; typedef std::vector<std::pair<std::string, CI_RecordInfo_Vector*> > MgrBlks; MgrBlks mgr_n_blks { {"T2M_NAME", NULL} }; // <--- line 59 

However, the compiler complains as follows:

 /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_pair.h: In constructor 'std::pair<_T1, _T2>::pair(_U1&&, _U2&&) [with _U1 = const char (&)[9], _U2 = long int, _T1 = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _T2 = CI_RecordInfo_Vector*]': tom.cpp:59: instantiated from here /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_pair.h:90: error: invalid conversion from 'long int' to 'CI_RecordInfo_Vector*' 

I assume that the "long int" is NULL, and for some reason I cannot convert it to a pointer. However, elsewhere on the structure map, I was able to compile something like

 foo["X"] = { NULL, "bar", 12 }; // first element is a pointer 

What is the difference?

+7
c ++ null pointers std-pair
source share
1 answer

The compiler correctly rejects this line:

 MgrBlks mgr_n_blks { {"T2M_NAME", NULL} }; 

In C ++ 11, std::pair has a template constructor that takes any types of arguments and then converts them to members:

 template<typename X, typename Y> pair(X&& x, Y&& y) : first(std::forward<X>(x)), second(std::forward<Y>(y)) { } 

NULL must be defined as 0 or 0L or something similar, so the output of the template argument outputs the arguments of the constructor template as const char* and (with GCC) long . The first type of argument is converted to std::string , but long not converted to CI_RecordInfo_Vector* , so the constructor cannot be called.

For another case with a structure map, there is no argument output, the assignment RHS must be converted to a structure type, in which case NULL used to directly initialize the first structure element, and is not first displayed as long and initializes a long , which cannot be converted to a pointer .

Do not use NULL in C ++ 11, nullptr was invented, in order to avoid precisely these problems, you should use it.

A possible workaround would be to cast the argument to the correct type:

 MgrBlks mgr_n_blks { {"T2M_NAME", (CI_RecordInfo_Vector*)NULL} }; 

but it’s easier and more understandable to use nullptr .

+14
source share

All Articles