Creating std::shared_ptr from a reference

  c++, pointers

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?

Source: Windows Questions C++

LEAVE A COMMENT