多态智能指针数组作为参数



我想要一个采用接口类指针的静态2D数组。

使用原始指针Base* rawr[5][5]可以很好地工作,但我希望使用智能指针,并且只将原始指针作为参数传递。

如何在不将参数更改为智能指针的情况下使代码正常工作?

class Base {};
class Child : public Base {};
void Foo(Base* array[5][5])
{
// Stuff
}
void OtherFoo(std::unique_ptr<Base> array[5][5])
{
// Stuff
}
int main()
{
std::unique_ptr<Base> rawr[5][5];

// argument of type "std::unique_ptr<Base, std::default_delete<Base>> (*)[5]" 
// is incompatible with parameter of type "Base *(*)[5]"
Foo(rawr);
// no suitable conversion function from 
// "std::unique_ptr<Base, std::default_delete<Base>>" to "Base *(*)[5]" exists
Foo(rawr[5][5]);

// expression must have class type but it has type 
// "std::unique_ptr<Base, std::default_delete<Base>> (*)[5]"
Foo(rawr.get());
// expression must have pointer-to-class type but it has type 
// "std::unique_ptr<Base, std::default_delete<Base>> (*)[5]"
Foo(rawr->get());

// This works 
OtherFoo(rawr);
}

新手问题+可能是重复的,但在谷歌上搜索了一段时间后,我没有看到答案,对不起:"(

如何在不将参数更改为智能指针的情况下使代码正常工作?

不能在需要原始指针数组的地方传递智能指针数组。然而,您可以有两个独立的数组-一个是智能指针数组,另一个是指向智能指针正在管理的对象的原始指针数组,例如:

class Base {
public:
virtual ~Base() = default; 
};
class Child : public Base {};
void Foo(Base* array[5][5])
{
// Stuff
}
void OtherFoo(std::unique_ptr<Base> array[5][5])
{
// Stuff
}
int main()
{
std::unique_ptr<Base> smartr[5][5];
Base* rawr[5][5];

// fill smartr as needed...
for (int i = 0; i < 5; ++i) {
for(int j = 0; j < 5; ++j) {
rawr[i][j] = smartr[i][j].get();
}
}
Foo(rawr);
OtherFoo(smartr);
}

最新更新