I am trying to use the auto_ptr in my code, but apparently something goes wrong.
auto_ptr<ClassType> Class(s.Build(aFilename)); //Instantiation of the Class object
int vM = s.GetM(Class);
int vS = s.Draw(Class);
The strange thing is that after the instantiation of Class, the Class object exist and so
by calling s.GetModelMean(Class), Class is not empty. But after exiting the function GetM,
Class is empty and so not usable anymore. A crash occurs when calling the function Draw.
I declared the functions the following way:
int GetM(auto_ptr<ClassType> aM);
It seems that the class is destroyed, but I do not understand why…
You shout not give an auto_ptr as an argument to a function. Either do:
or
or
(may be also with const – depends what you are doing with it). The first you would call the same way, the second function you would call like this:
the last without the star.
The reason is: GetM will copy the auto_ptr (not the Class object) and destroy the auto_ptr when it returns. The auto_ptr (which is a scope pointer or unique pointer – not a reference counter!) will than destroy Class.
Anyway: auto_ptr is very broken. Whenever possible (your compiler already supports some small parts of C++11), use std::unique_ptr and std::shared_ptr (last one does reference counting). unique_ptr will not allow you to mess around with it like that (since copying it is not allowed – which imho makes much more sense).