TFile and smart pointers

Hi everyone,
I recently began to learn to use smart pointers and I can’t understand why this declaration:

auto file = std::unique_ptr<TFile, decltype(&TFile::Close)> {
TFile::Open("test.root"),
&TFile::Close
};

gives me the following compile-time error:

In file included from /usr/include/c++/6.3.1/memory:81:0,
                 from test.cc:1:
/usr/include/c++/6.3.1/bits/unique_ptr.h: In instantiation of ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = TFile; _Dp = void (TFile::*)(const char*)]’:
test.cc:19:5:   required from here
/usr/include/c++/6.3.1/bits/unique_ptr.h:239:17: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘std::unique_ptr<_Tp, _Dp>::get_deleter<TFile, void (TFile::*)(const char*)>() (...)’, e.g. ‘(... ->* std::unique_ptr<_Tp, _Dp>::get_deleter<TFile, void (TFile::*)(const char*)>()) (...)’
    get_deleter()(__ptr);
    ~~~~~~~~~~~~~^~~~~~~

maybe it’s just a stupid mistake, can someone help me?

Hi,

No need for a custom deleter; simply let the unique_ptr delete the TFile object:

auto file = std::unique_ptr<TFile> {TFile::Open("test.root")};

Axel.

But is it always safe?

Yes, absolutely. Safe and little to no overhead compared to a regular TFile*.

Axel.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.