提升shared_ptr接口/对象

时间:2012-04-16 13:48:00

标签: c++ boost interface shared-ptr

假设我有一个API,它有两个方法可以相互结合使用:

boost::shared_ptr<IAsset> getAsset( const std::string & id );
void update( const Asset & asset );

我在另一个班级中有boost::shared_ptr<Asset> asset的成员变量。如果我这样做:

asset = otherObject->getAsset("first_asset");

// do some stuff

otherObject->update( *asset );

我收到错误:

      \boost\include\boost/smart_ptr/shared_ptr.hpp(378): error C2440: '<function-style-cast>' : cannot convert from 'boost::shared_ptr<T>' to 'boost::shared_ptr<T>'
      with
      [
          T=IAsset
      ]
      and
      [
          T=Asset
      ]
      No constructor could take the source type, or constructor overload resolution was ambiguous
      src\TestMethod.cpp(35) : see reference to function template instantiation 'boost::shared_ptr<T> &boost::shared_ptr<T>::operator =<IAsset>(boost::shared_ptr<IAsset> &&)' being compiled
      with
      [
          T=Asset
      ]
      \boost\include\boost/smart_ptr/shared_ptr.hpp(378): error C2228: left of '.swap' must have class/struct/union

我应该在此注意Asset的类定义确实扩展IAsset,如class Asset : virtual public IAsset {...}

有人可以告诉我正确的方法,因为我无权访问底层API吗?

3 个答案:

答案 0 :(得分:2)

这可能是不安全的转换,因此您必须使用dynamic pointer cast

(请注意,您不能使用虚拟基类中的static_cast。)

答案 1 :(得分:1)

我认为你对继承的使用是不正确的。如果update需要Asset,那么您需要向其发送Asset或其子类。 IAsset是一个超级班。

答案 2 :(得分:1)

因为您要将IAsset投射到需要向下投射的Asset

相关问题