2011-12-16 40 views
13

代码:`unique_ptr <T const []>`接受一个`T *`构造函数参数吗?

#include <memory> 
using namespace std; 

struct T {}; 

T* foo() { return new T; } 
T const* bar() { return foo(); } 

int main() 
{ 
    unique_ptr< T const >  p1(bar());  // OK 
    unique_ptr< T const [] > a1(bar());  // OK 

    unique_ptr< T const >  p2(foo());  // OK 
    unique_ptr< T const [] > a2(foo());  // ? this is line #15 
} 

用Visual C++ 10.0和MinGW克++ 4.4.1实施例的错误:

 
[d:\dev\test] 
> cl foo.cpp 
foo.cpp 
foo.cpp(15) : error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>' 
     with 
     [ 
      _Ty=const T [] 
     ] 
     C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE\memory(2509) : see declaration of 'std::unique_ptr<_Ty>::unique_ptr' 
     with 
     [ 
      _Ty=const T [] 
     ] 

[d:\dev\test] 
> g++ foo.cpp -std=c++0x 
c:\program files (x86)\codeblocks\mingw\bin\../lib/gcc/mingw32/4.4.1/include/c++/bits/unique_ptr.h: In function 'int main()': 
c:\program files (x86)\codeblocks\mingw\bin\../lib/gcc/mingw32/4.4.1/include/c++/bits/unique_ptr.h:379: error: deleted function 'std::unique_ptr<_Tp [], _Tp_Deleter>::unique_ptr(_Up*, typename std::enable_if<std::is_convertible::value, void>::type*) [with _Up = T, _Tp = const T, _Tp_Deleter = std::default_delete<const T []>]' 
foo.cpp:15: error: used here 

[d:\dev\test] 
> _ 

在我看来该阵列版本应该接受相同的隐式常量-添加作为非阵列版本。

不同之处在于数组版本不应接受指向派生类的指针,而这正是上面显示的机器。

代码是否有效?

如果代码在形式上无效,标准的措辞是否反映了意图(即,DR是否合适)?

如果不是第一个和是第二个,意向是否有缺陷(即同样是适当的DR)?

回答

9

缺陷报告可能是合适的。 §20.7.1.3.1说,

explicit unique_ptr(pointer p) noexcept; 
unique_ptr(pointer p, see below d) noexcept; 
unique_ptr(pointer p, see below d) noexcept; 

这些构造函数的行为相同,不同之处在于他们不接受指针类型可以转化成指针主模板。 [注意:一种实现技术是创建这些成员的私有模板重载。 - 注意]

这个想法显然是为了防止不适用于数组的导出到基准的转换。但它并不具体,并且也不允许简历资格转换。也许应该改为禁止指针转换(§4.10),而不是指针的所有转换。 “

+1

”可转换为指针的指针类型“ - 并且真的挑剔,这不是语言平坦不正确吗? `pointer`是一个可转换为指针的指针类型(例如,当描述概念时,如果某个函数返回一个“可转换为T”的类型,这并不意味着它不能是T本身)。但我不认为其目的是除了`指针`以及派生类型的指针;-) – 2011-12-16 10:38:26

相关问题