C++无法将对中的指针初始化为NULL

Cha*_*hap 7 c++ null pointers std-pair

我正在使用g ++ 4.4.7进行编译(当前不能更高),并使用-std=gnu++0x编译器开关,它应该允许第三行的语法.

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
Run Code Online (Sandbox Code Playgroud)

但是,编译器抱怨如下:

/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*'
Run Code Online (Sandbox Code Playgroud)

我假设"long int"是NULL,并且由于某种原因我无法将其转换为指针.然而在结构图的其他地方,我能够编译类似的东西

foo["X"] = { NULL, "bar", 12 }; // first element is a pointer
Run Code Online (Sandbox Code Playgroud)

有什么不同?

Jon*_*ely 15

编译器拒绝此行是正确的:

MgrBlks mgr_n_blks { {"T2M_NAME", NULL} };
Run Code Online (Sandbox Code Playgroud)

在C++ 11中std::pair有一个模板构造函数,它接受任何参数类型,然后将它们转换为成员:

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

NULL必须定义为00L类似的东西,因此模板参数推导将构造函数的模板参数推断为const char*和(使用GCC)long.第一个参数类型是可转换为std::stringlong不可转换为CI_RecordInfo_Vector*,因此无法调用构造函数.

对于带有结构映射的另一种情况,没有参数推导,赋值的RHS必须可转换为结构类型,并且在这种情况下NULL用于直接初始化结构的第一个成员,而不是首先推导为结构类型long和初始化a long,无法转换为指针.

不要NULL在C++ 11中使用,nullptr发明是为了避免这些问题,你应该使用它.

一种可能的解决方法是将参数转换为正确的类型:

MgrBlks mgr_n_blks { {"T2M_NAME", (CI_RecordInfo_Vector*)NULL} };
Run Code Online (Sandbox Code Playgroud)

但使用起来更简单,更清晰nullptr.