Re: Virtual Ctor Idiom and auto_ptr
Maxim Yegorushkin ha scritto:
Alberto Ganesh Barbati wrote:
[]
Returning an std::auto_ptr is better than returning a pointer for two
reasons:
[]
2) it also enforces that, in the sense that the cleanest idiom (i.e.:
hold the result in another auto_ptr) will properly manage custody
automatically, while any other "manual" way of keeping the custody
requires an explicit call to the release() method
Could you post a sample please? The only "manual" thing I could come
with, if I understand you correctly, is the following code, where
release is not necessary:
#include <memory>
int* f() { return new int(); }
int main()
{
std::auto_ptr<int> p(new int());
p.reset(f()); // no release call required
}
Ehr... this example f() does not *return* an std::auto_ptr... so I don't
understand what is the relationship with what I was saying.
I meant this:
// *returns* an std::auto_ptr
std::auto_ptr<int> f();
void legacy_function_that_takes_custody(int* p);
int main()
{
// idiom 1: automatically transfer custody by copying into
// an std::auto_ptr
std::auto_ptr<int> a = f();
// idiom 2: manually obtain custody by explicitly calling release()
legacy_function_that_takes_custody(f().release());
}
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]