samedi 25 mai 2019

Destructor throws exception when deriving from unique_ptr

I tried to hack into unique_ptr's deleter, but without compromising construct by right value (we can't override deleter since it's associated with the right value). So I decide to try deriving from unique_ptr, here is my code.

using OStreamPtr = std::unique_ptr<std::ostream>;

class MockOStreamPtr : public OStreamPtr {

 public:
  MockOStreamPtr(OStreamPtr&& rhs, MockOutputSystem* sys) : OStreamPtr(std::move(rhs)), sys_(sys) {}
  MockOStreamPtr(std::ostream* p, MockOutputSystem* sys) : OStreamPtr(p), sys_(sys) {}
  ~MockOStreamPtr() {
    std::cout << "~MockOStreamPtr" << std::endl;
    if (sys_) {
      std::cout << get()->good() << std::endl;  // this failed already
      sys_->manage(*this);
    }
  }

 protected:
  MockOutputSystem* sys_ = nullptr;
};

MSVC gives me an SEH exception on accessing ostream pointer during destruction, which I can't understand at all.

test case:

MockOutputSystem sys;
OStreamPtr s(sys.fopen("test_file.b"));
(*s) << "hello world";
s.release();  // failed here
EXPECT_EQ(sys.get_file("test_file.b"), "hello world");

Aucun commentaire:

Enregistrer un commentaire