简体   繁体   English

从引用创建 std::shared_ptr

[英]Creating std::shared_ptr from a reference

I'm running into an object lifetime issue when I write我在写作时遇到了 object 生命周期问题

std::ifstream input("/Users/d.a.hosek/CLionProjects/gftodvi/data/cmr10.2602gf");
GFReader reader {std::shared_ptr<std::ifstream>(&input)};

When the program concludes, it runs into an issue destroying things in my chain, saying that it's trying to free a pointer that wasn't allocated.当程序结束时,它遇到了一个问题,破坏了我的链中的东西,说它试图释放一个未分配的指针。

But if I do但如果我这样做

GFReader reader {std::make_shared<std::ifstream>("/Users/d.a.hosek/CLionProjects/gftodvi/data/cmr10.2602gf")};

then the problem goes away.然后问题就消失了。 I'm assuming I'm doing something wrong in the first call sequence when I create my std::shared_ptr but I don't really understand what it is.我假设我在创建std::shared_ptr时的第一个调用序列中做错了,但我真的不明白它是什么。 Can someone give me clear explanation of why the first call sequence fails?有人可以清楚地解释为什么第一个调用序列失败吗?

The first way is intended to take an existing heap-allocated resource and manage its lifetime.第一种方法旨在获取现有的堆分配资源并管理其生命周期。 You pass it a non heap allocated resource, violating its rules.你传递给它一个非堆分配的资源,违反了它的规则。

The second creates a new heap allocated resource and immediately manages it.第二个创建一个新的堆分配资源并立即管理它。 It even allocates the ref counting block adjacent to the object, to save on calls to ::new .它甚至分配与 object 相邻的引用计数块,以节省对::new的调用。

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

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