1

I'm running into an object lifetime issue when I write

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. Can someone give me clear explanation of why the first call sequence fails?

1
  • as a workaround, you can pass a shared_ptr with no-op deletor. (if you cannot modify GFReader to take a non-owning pointer) (and cannot dynamic-allocate input e.g. it comes from a parameter) Commented Mar 6, 2021 at 8:11

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.