在下面的代码中,函数
f()
可以调用不完整的class C
的unique_ptr<C>
的operator bool()
和operator *()
成员函数。然而,当函数g()
尝试为unique_ptr<X<C>>
调用相同的成员函数时,编译器突然需要一个完整的类型并尝试实例化X<C>
,然后失败了。由于某种原因,unique_ptr<X<C>>::get()
不会导致模板实例化,并且像h()
函数中所看到的那样编译正确。这是为什么?是什么让get()
与operator bool()
和operator *()
不同?#include <memory>
class C;
std::unique_ptr<C> pC;
C& f() {
if ( !pC ) throw 0; // OK, even though C is incomplete
return *pC; // OK, even though C is incomplete
}
template <class T>
class X
{
T t;
};
std::unique_ptr<X<C>> pX;
X<C>& g() {
if ( !pX ) throw 0; // Error: 'X<C>::t' uses undefined class 'C'
return *pX; // Error: 'X<C>::t' uses undefined class 'C'
}
X<C>& h() {
if ( !pX.get() ) throw 0; // OK
return *pX.get(); // OK
}
class C {};
h()
),并希望不会出现任何问题。 - Barnett