在VC++ 2013的C++头文件memory
中,我发现类unique_ptr
定义如下:
template<class _Ty, class _Dx> // = default_delete<_Ty>
class unique_ptr
{
...
};
让我感到困惑的是:模板参数没有默认类型,这是 C++11 标准所要求的。 (参见 here)
但是,我可以在没有任何警告或错误的情况下编译以下代码:
#include <memory>
using namespace std;
int main()
{
unique_ptr<int>(new int); // Should be OK! ???
// rather than unique_ptr<int, default_delete<int>>(new int);
}
为什么?
最佳答案
默认参数在前面的前向声明中指定:
// [memory:24]
_STD_BEGIN
#if _HAS_CPP0X
template<class _Ty>
struct default_delete;
template<class _Ty,
class _Dx = default_delete<_Ty> >
class unique_ptr;
#endif /* _HAS_CPP0X */
// [...]
// [memory:1276]
// TEMPLATE CLASS unique_ptr SCALAR
template<class _Ty,
class _Dx> // = default_delete<_Ty>
class unique_ptr
: private _Unique_ptr_base<_Ty, _Dx,
is_empty<_Dx>::value
|| is_same<default_delete<_Ty>, _Dx>::value>
{ // non-copyable pointer to an object
这是有效的,就像在函数定义之前为函数声明默认参数一样有效,例如
void foo(int x = 5);
void foo(int x) { /* ... */ }
[C++11: 14.1/10]:
The set of default template-arguments available for use with a template declaration or definition is obtained by merging the default arguments from the definition (if in scope) and all declarations in scope in the same way default function arguments are (8.3.6). [ Example:template<class T1, class T2 = int> class A; template<class T1 = int, class T2> class A;
is equivalent to
template<class T1 = int, class T2 = int> class A;
—end example ]
关于c++ - 为什么 VC++ 允许没有完整模板参数的模板类实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24362039/