简体   繁体   English

std :: weak_ptr:lock或shared_ptr构造函数?

[英]std::weak_ptr: lock or shared_ptr constructor?

There seem to be two ways to temporarily grab ownership of the resource pointed to by a weak_ptr : 似乎有两种方法可以临时获取weak_ptr指向的资源的所有权:

  1. Use lock() 使用lock()
  2. Pass the weak_ptr to a shared_ptr constructor weak_ptr传递给shared_ptr构造函数

Both of these produce a shared_ptr , with the lock returning a nullptr in the case that the weak_ptr is empty and the shared_ptr constructor throwing an exception. 这两个都产生一个shared_ptr ,在weak_ptr为空并且shared_ptr构造函数抛出异常的情况下,锁返回nullptr

So the question is: when should one or the other be used? 所以问题是:何时应该使用其中一种? Are there general guidelines or best practices related to this? 是否有与此相关的一般准则或最佳做法?

Copied from http://en.cppreference.com/w/cpp/memory/weak_ptr/lock 复制自http://en.cppreference.com/w/cpp/memory/weak_ptr/lock

Both this function and the constructor of std::shared_ptr may be used to acquire temporary ownership of the managed object referred to by a std::weak_ptr. 此函数和std :: shared_ptr的构造函数都可用于获取std :: weak_ptr引用的托管对象的临时所有权。 The difference is that the constructor of std::shared_ptr throws an exception when its std::weak_ptr argument is empty, while std::weak_ptr::lock() constructs an empty std::shared_ptr. 不同之处在于std :: shared_ptr的构造函数在其std :: weak_ptr参数为空时抛出异常,而std :: weak_ptr :: lock()构造一个空的std :: shared_ptr。

That leads me to believe that you pick which one to use based on whether you want an exception thrown or not. 这让我相信你根据是否要抛出异常来选择使用哪一个。 The constructor can be used when it must work, whereas lock can be used when it's possible that it won't work and you can check. 构造函数可以在必须工作时使用,而lock可以在它可能无法工作时使用,您可以检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM