TFile - casts - segmentation violations

Dear all,

I am using GCC 4.8.2 to compile on Ubuntu 14.04. I have had a look at the ownership issues, but it still puzzles me why the following expressions give a segmentation violation (even on v5.34.18):

What I thought was the most thoughtful :

TFile file("filename.root"); h = new TH1D(*dynamic_cast<TH1D*>(file.Get("hsit")))

(I didn’t expect this one to work but…) :

TFile file("filename.root"); h = new TH1D(*static_cast<TH1D*>(file.Get("hsit")))

Heap allocation and dynamic cast fail (I doesn’t make sense to me) :

TFile* file("filename.root"); h = new TH1D(*dynamic_cast<TH1D*>(file->Get("hsit")))

Ownership trick and dynamic cast :

TDirectory* CurrentDir = gDirectory;
TFile file("filename.root");
h = new TH1D(*dynamic_cast<TH1D*>(file.Get("hsit")))
CurrentDir->cd();

And why only these tricks work:

Heap allocation and static cast :

TFile* file("filename.root"); h = new TH1D(*static_cast<TH1D*>(file->Get("hsit")))

Ownership trick and static cast :

TDirectory* CurrentDir = gDirectory;
TFile file("filename.root");
h = new TH1D(*static_cast<TH1D*>(file.Get("hsit")))
CurrentDir->cd();

Thanks in advance,
Valérian

TFile file("filename.root"); // http://root.cern.ch/root/html534/TDirectoryFile.html#TDirectoryFile:Get TH1D *h; file.GetObject("hsit", h); if (!h) { std::cout << "hsit NOT found!" << std::endl; } else h->SetDirectory(gROOT); // (gROOT) or (0)

TDirectory *CurrentDir = gDirectory; TFile file("filename.root"); // http://root.cern.ch/root/html534/TDirectoryFile.html#TDirectoryFile:Get TH1D *h; file.GetObject("hsit", h); if (!h) { std::cout << "hsit NOT found!" << std::endl; } else h->SetDirectory(CurrentDir); if (CurrentDir) CurrentDir->cd();

Thank you for your reply, but could you explain at bit more ? Why do you have to perform “h->SetDirectory(gROOT)” ? I understand that “GetObject” is safer.

Also, in your comments you’re refering to : root.cern.ch/root/html534/TDirec … ryFile:Get

Where it advises to use a dynamic_cast:
MyClass obj = dynamic_cast<MyClass>(directory->Get(“some object of MyClass”));

This is exactly what I have tried in my first example. And I don’t get why it doesn’t work with a TH1D if it is supposed to work with a user-defined class “MyClass”.

Thanks,
Valérian

ROOT User’s Guide -> Object Ownership