gpt4 book ai didi

c++ - 将派生指针隐式转换为其相应基的引用

转载 作者:搜寻专家 更新时间:2023-10-31 01:44:14 25 4
gpt4 key购买 nike

我有一个看起来像这样的函数:

// this function might modify base_ptr
void SomeFunction(shared_ptr<Base> &base_ptr)
{ if(some_condition) { base_ptr = some_other_ptr; } }

我想用 shared_ptr 调用函数:

shared_ptr<Derived> d = ...;
SomeFunction(d);

虽然这不起作用。如果我使用普通指针,它也不起作用(即隐式转换为 Base* 和从 Derived*。一种解决方法是从 Derived 指针创建一个 Base 指针,然后将其传递给函数。

shared_ptr<Base> base = d;
SomeFunction(b);

但从编码的角度来看,这并不是很漂亮。它还增加了困惑和潜在的细微错误:

shared_ptr<Derived> d = derived;
shared_ptr<Base> b = derived;
SomeFunction(b);
// b and d might now be pointing to different things -- not good!

有更好的方法吗?

最佳答案

您尝试做的事情本质上是危险的,而 C++ 故意让它变得困难。考虑一下 C++ 是否允许您以您想要的方式调用 SomeFunction。然后你可以这样做:

struct Base {
};

struct Derived1 : Base {
void f1();
};

struct Derived2 : Base {
void f2();
};

void SomeFunction(shared_ptr<Base> &p)
{
p = make_shared<Derived2>(); // nothing wrong with converting
// a Derived2 pointer to a Base pointer.
}

int main()
{
shared_ptr<Derived1> d = make_shared<Derived1>();
SomeFunction(d); // An error, but what if it wasn't?
d->f1(); // Trying to call method f1 of a Derived2!
}

编译器将无法知道 dDerived1 指针更改为 Derived2 指针,因此它不会当您尝试调用 Derived2 的方法 f1 时,能够给您一个编译错误。

关于c++ - 将派生指针隐式转换为其相应基的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23829336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com