【发布时间】:2021-08-19 13:31:28
【问题描述】:
考虑以下代码:
#include <memory>
struct A {};
struct B : public A {};
void func( std::auto_ptr< A > ptr ) {}
int main() {
std::auto_ptr< B > b( new B() );
func( b );
}
我知道 auto_ptr 在 C++17 中已被删除并且被弃用了很长时间,但是,我使用的是 boost-python,它在其接口中不支持 unique_ptr(例如,请参阅 this )。我正在使用 g++ 7.5。
由于auto_ptr定义的转换构造函数(见(3)),隐式转换should be possible。但是,我得到了错误:
错误:从“std::auto_ptr”到“std::auto_ptr”的转换不明确
如果我改用unique_ptr,它定义了一个类似的构造函数(参见(6)),我会得到一个类似的错误:
错误:无法将“b”从“std::unique_ptr”转换为“std::unique_ptr”
这是为什么呢?
【问题讨论】:
-
对于
std::unique_ptr:应该是func( std::move(b) );... 但在A中缺少虚拟析构函数。 -
@Jarod42 好的,谢谢,这可以解决问题。但是,我仍然希望
auto_ptr在没有移动语义的情况下工作? -
如果您需要复制语义,
std::shared_ptr怎么样? -
明确转化pass (
func( std::auto_ptr< A >(b) );) -
我实际上需要移动语义(至少我认为这就是所谓的)。确切地说,我需要的是 constructor (3) of auto_ptr 所做的:"用 r 中保存的指针构造 auto_ptr。调用 r.release() 以获取对象的所有权。"
标签: c++ templates polymorphism