gpt4 book ai didi

c++ - 未能通过 shared_ptr 作为 shared_ptr 引用

转载 作者:行者123 更新时间:2023-12-02 09:51:28 25 4
gpt4 key购买 nike

在下面的代码中,我想通过 shared_ptr<Derived>作为 shared_ptr<Base>&争论,但失败了。
错误说,

cannot bind non-const lvalue reference of type 'std::shared_ptr<Base>&' to an rvalue of type 'std::shared_ptr<Base>'
所以看起来我只能通过 shared_ptr<Derived>const参数,但这不是我想做的,如何传递为 non-const ?
#include <iostream>
#include <memory>

class Base {
public:
virtual void say() {
std::cout << "I'm Base class" << std::endl;
}
};

class Derived : public Base {
public:
void say() {
std::cout << "I'm Derived class" << std::endl;
}
};

void foo(std::shared_ptr<Base>& obj) {
obj->say();
}

int main() {
auto base = std::make_shared<Base>();
foo(base);

auto derived = std::make_shared<Derived>();
foo(derived);
}

最佳答案

问题是 std::shared_ptr<Derived>可隐式转换为 std::shared_ptr<Base> , 但该转换会产生一个临时对象 - 不能绑定(bind)到非 const - 限定引用(foo 的参数就是这种情况)。
话虽如此,它看起来像 foo与所有权无关。然后最好将参数作为引用传递,而不是包装到智能指针中(传递 std::shared_ptr<T>& 应该只在可能从函数内部进行复制时进行,并且如果您总是获取拷贝,只需按值传递)。例如:

void foo(Base& obj) {
obj.say();
}
像下面这样调用。
auto base = std::make_shared<Base>();
foo(*base);

auto derived = std::make_shared<Derived>();
foo(*derived);
注意两个共享指针( *base*derived )的取消引用。但是,如果要复制,请按值传递(在传递临时值时有效)
void foo(std::shared_ptr<Base> obj) {
// ^^^ increases refcount
obj->say();
}
并让调用语法保持原样。

关于c++ - 未能通过 shared_ptr<Derived> 作为 shared_ptr<Base> 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64352097/

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