【发布时间】:2011-04-14 23:07:00
【问题描述】:
我正在使用 g++ 4.4.1 并想使用 nullptr,但我无法找到需要包含的头文件。它似乎也不是关键字,因为我使用它的尝试被拒绝为
error: 'nullptr' was not declared in this scope
【问题讨论】:
我正在使用 g++ 4.4.1 并想使用 nullptr,但我无法找到需要包含的头文件。它似乎也不是关键字,因为我使用它的尝试被拒绝为
error: 'nullptr' was not declared in this scope
【问题讨论】:
GCC 4.4.1 不支持nullptr。
在 GCC 4.6.0 中添加了对 nullptr 的支持:
http://gcc.gnu.org/gcc-4.6/changes.html
改进了对 即将推出的 C++0x ISO C++ 标准, 包括对 nullptr 的支持(谢谢 致 Magnus Fromreide),除了, 不受限制的联合,基于范围的 循环(感谢 Rodrigo Rivas Costa), 隐式删除的函数和 隐式移动构造函数。
对于早期版本的 GCC,如果您想尝试使用 nullptr,您可以尝试以下 SO 问题中的解决方法:
【讨论】:
__null 只是 NULL 在 GCC 上的定义。它不与nullptr 相同,因为它(显然)具有与NULL 相同的语义。没有理由使用__null。
我建议不要使用上面定义的nullptr,因为它可能很危险。如果你想使用nullptr,下面的说法应该是正确的。
sizeof(nullptr) == sizeof(void*) == sizeof(any pointer)
但是,sizeof(nullptr)(如上定义)将不符合此规则。它实际上会评估为sizeof(bad nullptr) = 1。
这是一个正确的实现。
#pragma once
namespace std
{
//based on SC22/WG21/N2431 = J16/07-0301
struct nullptr_t
{
template<typename any> operator any * () const
{
return 0;
}
template<class any, typename T> operator T any:: * () const
{
return 0;
}
#ifdef _MSC_VER
struct pad {};
pad __[sizeof(void*)/sizeof(pad)];
#else
char __[sizeof(void*)];
#endif
private:
// nullptr_t();// {}
// nullptr_t(const nullptr_t&);
// void operator = (const nullptr_t&);
void operator &() const;
template<typename any> void operator +(any) const
{
/*I Love MSVC 2005!*/
}
template<typename any> void operator -(any) const
{
/*I Love MSVC 2005!*/
}
};
static const nullptr_t __nullptr = {};
}
#ifndef nullptr
#define nullptr std::__nullptr
#endif
【讨论】:
我使用 -std=c++0x 来启用 gcc 4.6.3 的 nullptr 功能
【讨论】:
如果您没有支持 C++11 的最新 gcc,请尝试使用 NULL 而不是 nullptr。
【讨论】: