我有一个 vector>
对象。我正在插入一个 Derived
类型的对象,其中 Derived
继承 Base
,如下所示: container.push_back(boost::shared_ptr ;(new Derived()));
我现在想要调用一个引用 Derived
成员的函数,以便修改我刚刚插入的最后一个条目。这样,我最终就不会创建此 Derived
对象的临时实例。这就是我能够做到的: func(static_cast(&*container.back())->member);
这对我来说看起来真的很可怕-丑陋。但是,如果我尝试执行 func(static_cast(*container.back()).member);
,编译器会说我需要为 Derived
它采用 args (const Base&)
来将 Base 的实例转换为 Derived 的实例,我不需要在这里执行此操作...我只想引用我的Shared_ptr 指针就好像它是一个Derived*
,因为我知道它是因为我刚刚new
编辑了它。
I have a vector<boost::shared_ptr<Base>>
object. I'm inserting an object of type Derived
where Derived
inherits Base
like this: container.push_back(boost::shared_ptr<Base>(new Derived()));
I now want to call a function which takes a reference to a member of Derived
, in order to modify this last entry I just inserted. This way, I don't end up creating a temporary instance of this Derived
object. This is how I'm able to do it: func(static_cast<Derived*>(&*container.back())->member);
This looks really scary-ugly for me. But if I try to do func(static_cast<Derived>(*container.back()).member);
instead, the compiler says I need to provide a ctor for Derived
which takes the args (const Base&)
in order to convert an instance of Base to an instance of Derived, which I don't need to do here... I just want to refer to my shared_ptr pointer as though it were a Derived*
because I know it is because I just new
ed it.
发布评论
评论(3)
没有演员表。没有
Derived
的临时项。No casts. No temporaries of
Derived
.我会使用
dynamic_cast<>
,因为存储的对象实际上可能不是 Derived 类型(它可能是也从 Base 派生的 Derived_2)。您还可以转换为参考,使其看起来稍微整洁一些。
注意:
dynamic_cast<>
这就是为什么我通常更喜欢将dynamic_cast 与引用一起使用。但如果将其与指针一起使用,请务必在使用之前检查结果不为 NULL。
编辑更新的问题:
您需要一个引用
这将阻止它尝试调用构造函数。如果你 static_cast<>到 Derived 它将尝试创建一个对象。你真正想要的是一个参考。
I would use
dynamic_cast<>
as the object being stored may not actually be of type Derived (it may be a Derived_2 also derived from Base).You can also cast to references to make it look slightly neater.
Note:
dynamic_cast<>
Which is why I prefer to use dynamic_cast with references usually. But if you use it with a pointer be sure to check the result is not NULL before you use it.
Edit on the updated question:
You want a reference
This will stop it trying to call the constructor. If you static_cast<> to Derived it will try and create an object. What you really want is a reference.
您可以使用
static_pointer_cast
和dynamic_pointer_cast
在shared_ptr
之间进行转换:You can use
static_pointer_cast
anddynamic_pointer_cast
to cast betweenshared_ptr
s: