将shared_ptr传递给函数不起作用

Passing shared_ptr to function is not working

本文关键字:函数 不起作用 shared ptr      更新时间:2023-10-16

我有一个名为Fan的类型,每当我尝试写这个函数时:

void connect(shared_ptr<Fan>&);

它没有被编译,这就是我在终端中得到的:

fanBook_example.cpp:34:22: error: no matching function for call to 
âmtm::FanBookServer::connect(std::shared_ptr<mtm::Fan>&)â
fanBook_example.cpp:34:22: note: candidate is:
In file included from Fan.h:3:0,
from FanBookPost.h:5,
from mtm_ex4.h:36,
from fanBook_example.cpp:16:
FanBookServer.h:39:7: note: void mtm::FanBookServer::connect(int&)

我试图将sharedptr作为参数传递,但它不起作用,不知道该怎么做?谢谢

编辑:

我正在尝试实现连接函数,该函数应该以shared_ptr为例:

auto fan = std::make_shared<Fan>(1,"Bob");
server->connect(fan)

Fan类型位于Fan.h(包括在内),其内部命名空间称为mtm并且FanBookServer在名称空间mtm内。

始终从第一个编译器错误(或警告)开始,而不是最后一个。编译器错误倾向于"级联":编译器首先看到类似的东西

void connect(shared_ptr<Fan>&);

并发出类似的错误消息

test2.cc:2:14: error: no template named 'shared_ptr'; did you mean 'std::shared_ptr'?
void connect(shared_ptr<Fan>&);
^~~~~~~~~~
std::shared_ptr

根据编译器的特定版本,它很可能会用int替换未知类型,然后继续执行它的操作——这有助于在一次运行中给出尽可能多的错误。(这并不完全是讽刺;在极少数情况下,程序会有多个独立的语法错误,程序员会很高兴一次被告知所有这些错误。)

无论如何,在您的情况下,编译器会将std::shared_ptr<Fan>传递给原型为int&的函数(好吧,实际上是<unknown-type>&,但对这个编译器来说是一样的),因此它会抱怨。


在一个无关的问题上,您可能不需要通过引用传递shared_ptr本身——只有当您计划修改调用方的指针本身时(即,如果您将其用作out参数),这才有用。您可能应该使用void connect(shared_ptr<Fan> p)(如果它需要处理所有权问题)或void connect(const Fan& fan)(如果它不需要处理所有权)。