I was just reading through some old articles in the 'Why not develop new
language' thread and came across the finally debate.
Everytime I mention 'finally' to C++ programmers I get almost emotional
responses about why it is not needed in C++. I don't get that.
For example, consider the following code. Please note, I can only use
heap allocated objects in my current project (new/delete).
//
// Foo - Tries to foo. Can throw a FooException
//
void Foo()
{
try {
// Do your foo business that could throw a FooException
}
catch (...) {
// Cleanup your business
throw;
}
// Cleanup your business
}
Now, with finally I could do this:
void Foo()
{
try {
// Do your foo business that could throw a FooException
}
finally {
// Cleanup your business
}
}
Which I find *much* cleaner than the other example as there is no
need to do the cleanup twice.
Anyway, the debate is useless because we don't have finally. So my question
really is, how do people refactor the above to something nicer?
S.
Jul 22 '05
54 2909
Stefan Arentz wrote: Neh, we keep the beer in the fridge. The device is a MIPS based device with not too much RAM/Flash. Think <= 8MB. which needs to be shared with a kernel, libraries some tools.
It is not very special, you just can't use all nice tricks that are obvious on a normal 1GB workstation with a standard 80GB drive :)
8MB? C++ programs can execute in DOS systems with <= 640 KB RAM. And
that is too much too.
--
Ioannis Vranos http://www23.brinkster.com/noicys
"Ioannis Vranos" <iv*@guesswh.at .grad.com> wrote in message
news:ci******** **@ulysses.noc. ntua.gr... Dietmar Kuehl wrote:
Object should always be initialized, i.e. the above line shall be replaced by something like this if used at all:
| char * my_ptr = 0;
Why? This is a personal style and not mandatory.
It is "mandatory" if you want exception safe code. The above, without "=0"
is equivalent to:
char* my_ptr = rand();
What happens if/when new throws?
Jeff F
Ioannis Vranos wrote: Dietmar Kuehl wrote:
Object should always be initialized, i.e. the above line shall be replaced by something like this if used at all:
| char * my_ptr = 0;
Why? This is a personal style and not mandatory.
Correct, it is not mandatory. However, this "personal" style
reduces the potential for errors dramatically (not only in C++).
It also makes certain, IMO ill-advised, programming approachs,
like e.g. use of "try"-blocks, quite inattractive :-)
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - Software Development & Consulting
Jeff Flinn wrote: It is "mandatory" if you want exception safe code. The above, without "=0" is equivalent to:
char* my_ptr = rand();
Not exactly, but anyway.
What happens if/when new throws?
What happens?
--
Ioannis Vranos http://www23.brinkster.com/noicys
Dietmar Kuehl wrote: Correct, it is not mandatory. However, this "personal" style reduces the potential for errors dramatically (not only in C++).
As I have told many times in clc++, not really.
It also makes certain, IMO ill-advised, programming approachs, like e.g. use of "try"-blocks, quite inattractive :-)
May you expand on that?
--
Ioannis Vranos http://www23.brinkster.com/noicys
Niels Dybdahl wrote: Cleanup code are not part of the program logic, so it is very nice to
avoid it in the middle of the main code by putting it away in a destructor. In addition the destructor approach prevents programmers from forgetting cleanup code which leads to more stable applications. So it is not a workaround but a significant improvement.
Totally.
Designs should not duplicate behaviors. If two functions have the same lines
in their finally blocks, they duplicate those lines. Moving these to a
non-deterministic destructor simplifies the design.
Java's reason to exist is C++ memory leaks. Then they solved the wrong
problem. Non-deterministic destructors cause all kinds of trouble, leading
to klutzy work-arounds.
--
Phlip http://industrialxp.org/community/bi...UserInterfaces
Ioannis Vranos <iv*@guesswh.at .grad.com> writes: Stefan Arentz wrote:
Neh, we keep the beer in the fridge. The device is a MIPS based device with not too much RAM/Flash. Think <= 8MB. which needs to be shared with a kernel, libraries some tools. It is not very special, you just can't use all nice tricks that are obvious on a normal 1GB workstation with a standard 80GB drive :)
8MB? C++ programs can execute in DOS systems with <= 640 KB RAM. And that is too much too.
Yes, you can run C++ programs on a AVR with 16K flash too, but that is
not the point.
Sorry but no more smart ass answers on this one please. I *know* what
kind of memory constraints I have in my project.
S.
"Stefan Arentz" <st***********@ gmail.com> wrote in message
news:87******** ****@keizer.soz e.com... "Jeff Flinn" <NO****@nowhere .com> writes:
"Stefan Arentz" <st***********@ gmail.com> wrote in message news:87******** ****@keizer.soz e.com... Tom Widmer <to********@hot mail.com> writes:
> On 21 Sep 2004 14:32:39 +0200, Stefan Arentz
<st***********@ gmail.com> > wrote: > > > > >I was just reading through some old articles in the 'Why not
develop new > >language' thread and came across the finally debate. > > > >Everytime I mention 'finally' to C++ programmers I get almost
emotional > >responses about why it is not needed in C++. I don't get that. > > > >For example, consider the following code. Please note, I can only
use > >heap allocated objects in my current project (new/delete). > > So your current project isn't in standard C++, but rather a > company/personal dialect? I'm not sure we can help much with that...
Well, it is code for firmware of a small device. Not very small, but
small enough that something like STL or Boost is not an option. Templates probably
Is this because your compiler doesn't support STL/Boost? Or that you
"think" STL\Boost will require more memory?
It is because both memory and flash is sparse. And I know for a fact that
it does not fit.
Please adequately define "it"?
In the context of using std facilities in lieu of "finally", you'd only use
boost::scoped_a rray_ptr, or just use std::vector. With an optimizing
compiler, the size differences should be insignificant. Or by chance are you
looking at debug mode builds?
Jeff F
On 21 Sep 2004 16:03:38 +0200, Stefan Arentz <st***********@ gmail.com>
wrote: where the foo business uses stack based objects whose destructors do the cleanup. If your company doesn't allow that, then your company is using mackled C++, and might be better off with C# or Java. At the very least you can use std::auto_ptr. So that would mean stack based objects and references? Get rid of all pointers?
Rather, make sure any pointers are controlled by objects.
It would probably mean a complete redesign of some things,but I am willing to look into it. Is this the RAII stuff other people were talking about?
Yes. Basically, rather than:
Foo* f = 0;
try
{
f = new Foo();
f->bar();
}
catch(...)
{
delete f;
throw;
}
delete f;
You would do:
Foo f;
f.bar();
or, if necessary,
std::auto_ptr<F oo> f(new Foo);
f->bar();
Tom
red floyd wrote: Rolf Magnus wrote:
That's what std::auto_ptr is for:
void bar() { try { SomeObject instace; std::auto_ptr<c har> my_ptr(new char[987]); // do something instace.doSomeh ting() // throws an exception let's say MyExec } catch(MyExec &exc) { // error handling } }
That's double-plus-ungood Rolf. As I understand it, std::auto_ptr<> 's destructor calls delete, not delete[]. So you invoked UB.
Yes, I realized that after posting. I cancelled the posting, but it seems it
was too late already. Anyway, you could still write some auto_ptr
equivalent for arrays, or use something from boost. Imho, an auto_ptr for
arrays should be part of the standard library. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: melledge |
last post by:
Worldwide Debate on Open Data Highlighted at XTech 2005
Presentation Topics Include Web Services, RSS, FOAF, OAI, Open Access,
and More;Special Focus on OpenOffice.org's Influence on Standards and
New Technologies
Alexandria, Va. - April 20, 2005 - The opportunities and challenges
of "open data" on the Web will be the focus of a new educational
track at XTech 2005, the premier European conference for developers and
managers working with...
|
by: VB Programmer |
last post by:
Variable scope doesn't make sense to me when it comes to Try Catch Finally.
Example: In order to close/dispose a db connection you have to dim the
connection outside of the Try Catch Finally block. But, I prefer to dim them
"on the fly" only if needed (save as much resources as possible). A little
further... I may wish to create a sqlcommand and datareader object ONLY if
certain conditions are met. But, if I want to clean these up in the...
|
by: berns |
last post by:
Hi All,
A coworker and I have been debating the 'correct' expectation of
evaluation for the phrase a = b = c. Two different versions of GCC
ended up compiling this as b = c; a = b and the other ended up
compiling it as a = c; b = c. (Both with no optimizations enabled).
How did we notice you may ask? Well, in our case 'b' was a memory
mapped register that only has a select number of writable bits. He
claims it has been a 'C...
|
by: Wells |
last post by:
Debate Simmering in US Over Regulation of Internet
A heated debate is shaping up in Washington about a concept some
activists are calling Internet network neutrality, known more popularly
as net neutrality. At issue are calls for the U.S. government to
regulate the Internet, and, in effect, opponents say, determine which
companies get bigger shares of the profits.
To read the full text, please go to:...
|
by: John A Grandy |
last post by:
I'm in a vigorous debate at my work regarding objects assuming knowledge of
the type their containing object.
This debate pertains specifically to ASP.NET, but I have decided to post in
the C# forum because this is where most of the OO gurus hang out, and I view
this as a fundamental issue of OO design.
In ASP.NET, objects of type WebForm and UserControl have an intrinsic Page
property which refers to their containing Page.
| |
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |