应该是`unique_ptr< T const []>`接受`T *`构造函数参数?

时间:2011-12-16 07:46:36

标签: c++ c++11 standards unique-ptr

代码:

#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 g ++ 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]
> _

在我看来,数组版本应该接受与非数组版本相同的隐式const添加。

不同之处在于数组版本不应该接受指向派生类的指针,而这显然是上面提到的机制。

代码有效吗?

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

如果第一个没有,第二个是,那么意图是否有缺陷(即,再次适用DR)?

1 个答案:

答案 0 :(得分: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;
  

这些构造函数与主模板中的行为相同,只是它们不接受可转换为指针的指针类型。 [注意:一种实现技术是创建这些成员的私有模板化重载。 - 结束说明]

这个想法显然是为了防止无法使用数组的派生到基础的转换。但它是非特定的,也禁止cv资格转换。也许它应该改为禁止指针转换(§4.10),而不是指针的所有转换。

相关问题