我目前正在嘗試使用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