我正在与两个不同的最终用户一起使用一个库,其中一个正在使用gcc 4.5.3,另一个正在使用gcc 4.6.3。该库使用新的C++ 11智能指针(特别是unique_ptr),并在gcc 4.5.3上编译良好。但是,在这两个版本之间,gcc开始支持nullptr,因此unique_ptr的API进行了更改,以更紧密地匹配标准。现在,以下代码从正常变为模糊

unique_ptr up( new int( 30 ) );
...
if( up == 0 ) // ambiguous call now to unique_ptr(int) for 0

有没有一种干净的方法(即,下一句)来更改上述if语句,以便它可以与nullptr和不与nullptr一起使用?我想避免进行配置检查,如果可能的话,再避免如下所示的宏(我认为它将起作用)
#if defined NULLPOINTER_AVAILABLE
  #define NULLPTR (nullptr)
#else
  #define NULLPTR (0)
#endif

还是这是获得我正在寻找的行为的唯一方法?

最佳答案

您遇到了什么错误?

#include <iostream>
#include <memory>
int main() {
 using namespace std;
 unique_ptr<int> up( new int( 30 ) );
 if (up == 0)
     cout << "nullptr!\n";
 else cout << "bam!\n";
}

使用g++ -std=c++0x -Wall nullptr.cpp -o nullptr(gcc 4.6.2)可以正常编译。

另外,请阅读Stroustrup和Sutter关于nullptrN2431论文,其中一个示例中明确列出了类似用法(与0进行比较)。

关于c++ - unique_ptr,nullptr并支持gcc 4.5.x和4.6.x,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10864329/

10-16 01:02