简体   繁体   English

C++ 右值 shared_ptr 和右值 weak_ptr

[英]C++ rvalue shared_ptr and rvalue weak_ptr

std::shared_ptr<std::string> test() {
  return std::make_shared<std::string>("sdsd");
}
cout << *test() << endl;

The above code works.上面的代码有效。 Can someone please let me know where is the "sdsd" string stored.有人可以让我知道“sdsd”字符串存储在哪里吗? I was expecting it to error out as rvalue is a temporary object. Where is the rvalue copied to and stored in?我原以为它会出错,因为右值是一个临时值 object。右值复制到并存储在何处?

With weak_ptr使用 weak_ptr

std::weak_ptr<std::string> test() {
  return std::make_shared<std::string>("sdsd");
}
  cout << *test().lock() << endl;

Interestingly the above code errors out.有趣的是,上面的代码出错了。 What's the difference?有什么不同?

In

std::shared_ptr<std::string> test() {
  return std::make_shared<std::string>("sdsd");
}

the constructed shared_ptr is returned and lives on as a temporary variable long enough to be used by the caller before going out of scope and freeing the string allocated by make_shared .构造的shared_ptr被返回并作为一个临时变量存在足够长的时间以供调用者在退出 scope 并释放由make_shared分配的string之前使用。

The "sdsd" string is stored in dynamic storage owned by the returned shared_ptr . “sdsd” string存储在返回的shared_ptr 拥有的动态存储中。

In

std::weak_ptr<std::string> test() {
  return std::make_shared<std::string>("sdsd");
} 

the shared_ptr wasn't returned and went out of scope, taking the string allocated by make_shared with it. shared_ptr没有返回并从 scope 中取出,带走了make_shared分配的string Since this was the only existing copy of the shared_ptr this leaves the returned temporary weak_ptr variable connected to an expired share_ptr .由于这是shared_ptr的唯一现有副本,因此返回的临时weak_ptr变量连接到过期的share_ptr If you test the return value of lock you'll see it's a default-constructed shared_ptr holding a null pointer.如果您测试lock的返回值,您会看到它是一个默认构造的shared_ptr ,其中包含一个 null 指针。

Documentation for std::weak_ptr::lock .std::weak_ptr::lock的文档

The "sdsd" string isn't stored anywhere after test returns. test返回后,“sdsd” string不会存储在任何地方。 It departed when the shared_ptr that owned it went out of scope.当拥有它的shared_ptr超出 scope 时,它就离开了。

The above code works.上面的代码有效。 Can someone please let me know where is the "sdsd" string stored.有人可以让我知道“sdsd”字符串存储在哪里吗? I was expecting it to error out as rvalue is a temporary object. Where is the rvalue copied to and stored in?我原以为它会出错,因为右值是一个临时值 object。右值复制到并存储在何处?

The memory was allocated in the call to make_shared . memory 是在调用make_shared时分配的。

Interestingly the above code errors out.有趣的是,上面的代码出错了。 What's the difference?有什么不同?

The difference is that the lock operation on a weak_ptr can fail if there does not exist at least one shared_ptr to the object. That's the purpose of weak_ptr -- to allow the object to be freed and access it only if it still exists.不同之处在于,如果不存在至少一个指向 object 的shared_ptr ,则对weak_ptrlock操作可能会失败。这就是weak_ptr的目的——允许释放 object 并仅在它仍然存在时访问它。

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

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