我目前正在尝试使用Howard Hinnant's unique_ptr implementation,并且遇到编译错误。下面是一些示例代码:在这种情况下,Hinnant的unique_ptr实现是否错误地将派生对象转换为基类?
struct Base {};
struct Derived : public Base {};
void testfun(boost::unique_ptr<Base>);
void test()
{
unique_ptr<Derived> testDerived;
unique_ptr<Base> testBase(move(testDerived)); // ok, construct base explicitly from derived
testfun(move(testBase)); // ok, pass base to testfun which expects base
testfun(unique_ptr<Base>(move(testDerived))); // ok, explicitly converts to unique_ptr<Base>
testfun(move(testDerived)); // error on this line
}
我得到的错误是
In function 'void test()':
error: no matching function for call to 'boost::unique_ptr<Base, boost::default_delete<Base> >::unique_ptr(boost::unique_ptr<Base, boost::default_delete<Base> >)'
note: candidates are: boost::unique_ptr<T, D>::unique_ptr(boost::detail_unique_ptr::rv<boost::unique_ptr<T, D> >) [with T = Base, D = boost::default_delete<Base>]
note: boost::unique_ptr<T, D>::unique_ptr(boost::unique_ptr<T, D>&) [with T = Base, D = boost::default_delete<Base>]
error: initializing argument 1 of 'void testfun(boost::unique_ptr<Base, boost::default_delete<Base> >)' from result of 'boost::unique_ptr<T, D>::unique_ptr(boost::unique_ptr<U, E>, typename boost::enable_if_c<((((! boost::is_array<U>::value) && boost::detail_unique_ptr::is_convertible<typename boost::unique_ptr<U, boost::default_delete<U> >::pointer,typename boost::detail_unique_ptr::pointer_type<T, D>::type>::value) && boost::detail_unique_ptr::is_convertible<E,D>::value) && ((! boost::is_reference<D>::value) || boost::is_same<D,E>::value)), void>::type*) [with U = Derived, E = boost::default_delete<Derived>, T = Base, D = boost::default_delete<Base>]'
这似乎是有问题的行应该不会失败。这是实现中的一个错误,由于缺少C++ 0x语言特性而导致实现受到限制,或者是对unique_ptrs规则的误解?
(注意,我知道,因为我动了同样的事情不止一次这将不会在运行时正常工作;我只是想弄清楚编译时错误。)
大概描述的关键部分是“这个仿真的目的捕获** C++ 0X unique_ptr的大部分行为**“。我认为这意味着并非所有的行为都在那里。 – 2010-03-02 20:05:53
以下是导致C++ 03的这种行为的论文:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2000/n1232.pdf – 2010-03-02 20:40:12