U
Urs Thuermann
How can I cleanly and elegantly keep a locally created object beyond
the lexical block it is created in? Say I have a class Item with no
default constructor, but a copy constructor and code like this:
void some_func() {
my_queue.lock();
Item i = my_queue.get_item();
my_queue.unlock();
// do something with Item i
}
I now want to unlock() the my_queue even if get_item() throws an
exception. But both, a try-catch block and RAII would make the
variable Item i local so I cannot work on it after that block, e.g.
void some_func () {
// Cannot define Item i here since it has no default ctor.
try {
my_queue.lock();
Item i = ...
my_queue.unlock();
} catch (...) {
my_queue.unlock();
}
// cannot work with Item i here
}
I cannot define Item i before that block, since I have no default
ctor. Adding such a ctor that leaves i mostly uninitialized and
defining an assignment operator looks very unclean. Also something
like this
void some_func() {
Item *i;
try {
...
i = new Item(my_queue.get_item());
...
} catch ...
...
}
// do something with i
delete i;
}
looks very unclean and cumbersome, unnecessarily creates dynamic
memory overhead, and it also introduces the next resource leak if the
"do something with i" can throw an exception.
The cleanest solution I can currently think of is to put the try{}
block into a separate function and to return the Item to some_func().
Is there a simpler and cleaner way?
urs
the lexical block it is created in? Say I have a class Item with no
default constructor, but a copy constructor and code like this:
void some_func() {
my_queue.lock();
Item i = my_queue.get_item();
my_queue.unlock();
// do something with Item i
}
I now want to unlock() the my_queue even if get_item() throws an
exception. But both, a try-catch block and RAII would make the
variable Item i local so I cannot work on it after that block, e.g.
void some_func () {
// Cannot define Item i here since it has no default ctor.
try {
my_queue.lock();
Item i = ...
my_queue.unlock();
} catch (...) {
my_queue.unlock();
}
// cannot work with Item i here
}
I cannot define Item i before that block, since I have no default
ctor. Adding such a ctor that leaves i mostly uninitialized and
defining an assignment operator looks very unclean. Also something
like this
void some_func() {
Item *i;
try {
...
i = new Item(my_queue.get_item());
...
} catch ...
...
}
// do something with i
delete i;
}
looks very unclean and cumbersome, unnecessarily creates dynamic
memory overhead, and it also introduces the next resource leak if the
"do something with i" can throw an exception.
The cleanest solution I can currently think of is to put the try{}
block into a separate function and to return the Item to some_func().
Is there a simpler and cleaner way?
urs