【问题标题】:C++ implicit conversion of unique_ptr / auto_ptr to base type not working?将 unique_ptr / auto_ptr 隐式转换为基本类型不起作用?
【发布时间】: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&lt; A &gt;(b) );)
  • 我实际上需要移动语义(至少我认为这就是所谓的)。确切地说,我需要的是 constructor (3) of auto_ptr 所做的:"用 r 中保存的指针构造 auto_ptr。调用 r.release() 以获取对象的所有权。"

标签: c++ templates polymorphism


【解决方案1】:

看来编译器认为它是模棱两可的,因为operator()转换和constructor类型转换在auto_ptr中排名相同。编译器错误非常清楚地表明它无法在 2 次转换之间进行选择:

../src/test_curl_pop3.cpp:26:10: error: conversion from ‘std::auto_ptr<B>’ to ‘std::auto_ptr<A>’ is ambiguous
  func( b );
          ^
In file included from /usr/include/c++/5/memory:85:0,
                 from ../src/test_curl_pop3.cpp:9:
/usr/include/c++/5/backward/auto_ptr.h:279:9: note: candidate: std::auto_ptr< <template-parameter-1-1> >::operator std::auto_ptr<_Up>() [with _Tp1 = A; _Tp = B]
         operator auto_ptr<_Tp1>() throw()
         ^
/usr/include/c++/5/backward/auto_ptr.h:125:9: note: candidate: std::auto_ptr< <template-parameter-1-1> >::auto_ptr(std::auto_ptr<_Up>&) [with _Tp1 = B; _Tp = A]
         auto_ptr(auto_ptr<_Tp1>& __a) throw() : _M_ptr(__a.release()) { }
         ^
../src/test_curl_pop3.cpp:20:6: note:   initializing argument 1 of ‘void func(std::auto_ptr<A>)’
 void func( std::auto_ptr<A> p ) {}

【讨论】:

    猜你喜欢
    • 2013-08-11
    • 2021-02-18
    • 2016-11-15
    • 1970-01-01
    • 2016-04-12
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    相关资源
    最近更新 更多