[英]No viable conversion std::weak_ptr to std::shared_ptr for method call
I am able to convert back and forth inline. 我能够来回内联转换。
std::shared_ptr<sfg::Notebook> mNotebook = ...;
std::weak_ptr<sfg::Notebook> weakNotebook(mNotebook);
std::shared_ptr<sfg::Notebook> strongNotebook(weakNotebook);
When I attempt to pass it to a method, I get the error: 当我尝试将其传递给方法时,出现错误:
"No viable conversion between std::weak_ptr<sfg::Notebook> to std::shared_ptr<sfg::Notebook>."
I am calling the method normally, and the method looks like: 我正常调用该方法,该方法如下所示:
onNotebookLeftClick(weakNotebook);
void onNotebookLeftClick(std::shared_ptr<sfg::Notebook> notebook) {
}
I am using OS X (10.10.2). 我正在使用OS X(10.10.2)。
The shared_ptr
constructor you're trying to use is explicit
. 您要使用的shared_ptr
构造函数是explicit
。
template< class Y >
explicit shared_ptr( const std::weak_ptr<Y>& r );
Your first example 你的第一个例子
std::shared_ptr<sfg::Notebook> strongNotebook(weakNotebook);
works because you're using direct initialization, which works with explicit
constructors. 之所以有效,是因为您使用的是直接初始化,该初始化与explicit
构造函数一起使用。 You'd have the same problem if you used copy initialization instead 如果您使用副本初始化来代替,则会遇到同样的问题
std::shared_ptr<sfg::Notebook> strongNotebook = weakNotebook; // this will fail
To fix your error, do one of the following 要解决您的错误,请执行以下任一操作
onNotebookLeftClick(std::shared_ptr<sfg::Notebook>{weakNotebook});
or 要么
onNotebookLeftClick(weakNotebook.lock());
Note that there's a difference between the two methods. 请注意,两种方法之间存在差异。 If the weak_ptr
has expired
, the first solution will throw std::bad_weak_ptr
, while the second option will construct an empty shared_ptr
in that case. 如果weak_ptr
已expired
,则第一个解决方案将抛出std::bad_weak_ptr
,而第二个选项将在这种情况下构造一个空的shared_ptr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.