Re: Scope vs. point of construction for an object
In article
<987184e0-8d81-482b-a588-55b789f46b7b@u28g2000hsc.googlegroups.com>,
Alan McKenney <alan_mckenney1@yahoo.com> wrote:
(Cf.: "separate the declaration and construction of a local variable")
I've run into a situation with a class from a 3rd-party vendor, where:
1. There's no copy constructor or assignment operator.
2. The constructor may throw.
3. I need to use the object at various points in the code.
The sample code has the object being local and one big
"try" block around all the code that uses it. I would prefer
to have the "try" block just around where the object is
constructed, but then the object goes out of scope at
the end of the "try" block.
The obvious approach -- use a pointer and "new" -- seems sort of ugly:
T *t_ptr = 0;
try { t_ptr = new T( /* long complicated list of constructor
arguments */ ); } catch (...) { /* stuff */ }
// use t_ptr
delete t_ptr; // don't forget to delete it
Is there a way that keeps the non-pointer syntax?
Even better would be if I could put it into an object.
I realize it's technically still a pointer, but why not use auto_ptr
instead:
std::auto_ptr<T> t_ptr;
try { t_ptr.reset(new T(/*args*/); } catch (...) { /*stuff*/ }
// use t_ptr
// no delete necessary
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]