gpt4 book ai didi

c++ - 在 C++ 中的 unique_ptr 之间进行转换

转载 作者:太空狗 更新时间:2023-10-29 20:13:25 27 4
gpt4 key购买 nike

我有以下 C++11 结构:

#include <vector>
#include <memory>

class X {
public:
void f(void) { }
};

class Y : public X {
public:
void g(void) { }
};

class A {
private:
std::vector <std::unique_ptr <X> > xs;
public:
void addX(std::unique_ptr <X> &ref) {
xs.push_back(std::move(ref));
}
};

int main() {
A a;

std::unique_ptr <Y> y(new Y());
y->f();
y->g();

std::unique_ptr <X> x(y.release());
a.addX(x);

return 0;
}

在主函数中,我试图构建一个类型为 Y 的对象,然后将其添加到 a 的 X 对象的 vector 中。但是,我不能直接说a.addX(y)作为std::unique_ptr <Y>无法转换为 std::unique_ptr <X>& .这就是为什么我想出解决方法,我用释放的内部指针 y 初始化另一个唯一指针 x。

虽然这可行,但它似乎不是最佳解决方案。有没有更好的方法来传递 std::unique_ptr<Y> 类型的对象?作为 std::unique_ptr<X>& 类型的参数?

谢谢, - 斯坦

最佳答案

std::unique_ptr 已经提供了正确的重载,但您需要 std::move 才能使用它们,因为 unique_ptr 不可复制:

std::unique_ptr<X> x;
std::unique_ptr<Y> y { new Y };
x = std::move(y);

对于非常具体的问题,没有强制转换可能,如果您需要通过引用接收子类的 unique_ptr,则使用模板函数。

template < typename T, typename = typename std::enable_if< std::is_base_of<X,T>::value>::type >
void foo( std::unique_ptr<T> & ) {
}

最后,由于我们的想法是获得指针的所有权,如果您通过右值引用传递 unique_ptr,这将如您所愿。

void bar( std::unique_ptr<X> && ) {
}
// then
bar( std::move(y) );

关于c++ - 在 C++ 中的 unique_ptr 之间进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21580280/

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