【发布时间】:2016-09-15 09:30:20
【问题描述】:
在下面的代码中,函数f()可以调用unique_ptr<C>的成员函数operator bool()和operator *(),用于不完整的class C。但是,当函数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 {};
【问题讨论】:
-
我在 Visual Studio 2013 中编译您的代码没有问题。您使用什么编译器?
-
我使用 Visual Studio 2015、GNU 和 Clang 进行了测试。
-
如果单独使用每行带有“错误”的代码是否都会出错?还是只有在同一个函数中有两个时才会出错?
-
是的,每一行都有一个错误。
-
@Barry 不幸的是,您链接为重复的问题中提供的答案超出了我的想象。我只是打算使用解决方法(如
h())并希望我不会以某种方式被烧毁。