【发布时间】:2020-01-30 12:39:27
【问题描述】:
我编写了以下使用 unique_ptr<Derived> 的代码,其中应该是 unique_ptr<Base>
class Base {
int i;
public:
Base( int i ) : i(i) {}
int getI() const { return i; }
};
class Derived : public Base {
float f;
public:
Derived( int i, float f ) : Base(i), f(f) {}
float getF() const { return f; }
};
void printBase( unique_ptr<Base> base )
{
cout << "f: " << base->getI() << endl;
}
unique_ptr<Base> makeBase()
{
return make_unique<Derived>( 2, 3.0f );
}
unique_ptr<Derived> makeDerived()
{
return make_unique<Derived>( 2, 3.0f );
}
int main( int argc, char * argv [] )
{
unique_ptr<Base> base1 = makeBase();
unique_ptr<Base> base2 = makeDerived();
printBase( make_unique<Derived>( 2, 3.0f ) );
return 0;
}
我预计这段代码不会编译,因为根据我的理解 unique_ptr<Base> 和 unique_ptr<Derived> 是不相关的类型,unique_ptr<Derived> 实际上并不是从 unique_ptr<Base> 派生的,所以分配不应该工作。
但多亏了一些魔法,它起作用了,我不明白为什么,或者即使这样做是安全的。 谁能解释一下?
【问题讨论】:
-
智能指针是为了丰富指针的功能,而不是限制它。如果这不可能,
unique_ptr在存在继承的情况下将毫无用处 -
“但多亏了它的一些魔法”。几乎,你得到了 UB,因为
Base没有虚拟析构函数。
标签: c++ templates inheritance unique-ptr