473,800 Members | 2,332 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Style (or otherwise?) question: creating temporary to invoke function

Let's say you're in some function , and you want to accomplish some task x
that is provided for you by a class, A.
Which of these do you prefer, and is there a technical reason for it? (This
is actually the sort of thing that might be
provided for with a static class function, but one is not provided in this
case - an instance must be created.)

void f()
{
A a;
a.x();

A* p = new A();
p->x();
delete p;

A().x();
}
Jul 22 '05
23 1323
E. Robert Tisdale wrote:
...
If class 'A' doesn't have any internal state
or you don't care about that state,


Why should that make a difference?
...


What I meant to say is that it one cares to examine the internal state
of the 'A' object _after_ the operation, one has to declare a named
object of type 'A'. Otherwise, a temporary will do just fine.

--
Best regards,
Andrey Tarasevich

Jul 22 '05 #21
"David Harmon" <so****@netcom. com> wrote in message
news:40******** *******@news.we st.earthlink.ne t...
On Sat, 17 Apr 2004 00:19:50 +0300 in comp.lang.c++, "Ioannis Vranos"
<iv*@guesswh.at .emails.ru> wrote,
A a;
a.x();

A* p = new A();
p->x();
delete p;

Do the second if for some reason you can't do the first.


You would never allocate with 'new' for such a thing where you don't
even care about personally controlling the lifetime of the object. It
belongs only on the stack.

As i said to him: "Do the second if for some reason you can't do the first".
That means that for whatever reason he can't do the first (e.g. the object
does not fit in the stack), he should do the second.
And if for some reason it needed to be allocated with 'new', that would
still be wrong.

Then your general suggestion is never use new?
If x() throws an exception, the allocated object is
leaked. Horrors! If you must go this route, the minimum acceptable is

std::auto_ptr<A > p(new A);
p->x();

Relax. If A::x() can throw an exception he is supposed to catch it, else the
program will terminate anyway. And new has nothing to do with it.


Ioannis Vranos

Jul 22 '05 #22
"Ioannis Vranos" <iv*@guesswh.at .emails.ru> wrote in message
news:c5******** ***@ulysses.noc .ntua.gr...

Relax. If A::x() can throw an exception he is supposed to catch it, else the program will terminate anyway. And new has nothing to do with it.

I do not like to work on assumptions, but if we assume that he uses many A
objects in many different places, and wants to catch the hypothetical
exception that A::x() throws, in some levels distance, he can use auto_ptr
as you suggested or some container.

But all these are assumptions, we have no information on what the OP is
actually doing.


Regards,

Ioannis Vranos

Jul 22 '05 #23
>> A* p = new A();
p->x();
delete p; // Never!


Leaving a reference lying around
to an object that should never be reference again
is an invitation for trouble.


I find it convenient to do the following to increase the
probability that the program will crash if the pointer is
used again...

delete p;
p = 0;

I also put the critical member variables to an invalid value
in the destructor when it is not too much time consuming (so
the program will more likely crash if there is a pointer to
this object somewhere else).

Other useful tricks ?

Benoit

Jul 22 '05 #24

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
3836
by: David MacQuigg | last post by:
I have what looks like a bug trying to generate new style classes with a factory function. class Animal(object): pass class Mammal(Animal): pass def newAnimal(bases=(Animal,), dict={}): class C(object): pass C.__bases__ = bases dict = 0
1
2686
by: xtra | last post by:
Hi Folk I have written a module that allows you to type a bunch of commands in the immediate window, for quick access to information when you are creating VB code. Here it is, it may be helpful to you (I find it pretty fast and friendly).... Some of it is specific to my database (I left out many as well which were too specific), so you will have to rewrite it for yours, but you may find it useful.... Any questions, please ask. Typing...
8
2394
by: Todd Smith | last post by:
I'm wondering if anyone knows where I can learn a good programming method for creating windows apps. I'm just starting to learn windows programming with MSVC++ 6.0. I want to learn low level windows programming in C first. I don't want to learn any bad habits by hacking away at code until I get something to work. Specifically, I'd like to learn how to set up and plan out a C windows project and break it down into pieces of code that will...
31
2022
by: Christopher Benson-Manica | last post by:
How about your if/else if/else constructs? Being nitpicky like any good C programmer, I'm in the process of transforming code written like if( cond ) { ... } else if( some_other_cond ) { ... } else
144
6980
by: Natt Serrasalmus | last post by:
After years of operating without any coding standards whatsoever, the company that I recently started working for has decided that it might be a good idea to have some. I'm involved in this initiative. Typically I find that coding standards are written by some guy in the company who has a way of coding that he likes and then tries to force everybody else to write code the way he likes it, not for any rational reason, but simply for the...
83
15635
by: rahul8143 | last post by:
hello, what is difference between sizeof("abcd") and strlen("abcd")? why both functions gives different output when applied to same string "abcd". I tried following example for that. #include <stdio.h> #include <string.h> void main() { char *str1="abcd";
1
1838
by: Mladen Adamovic | last post by:
Why is memory safe that function allocate inner object and return its result? That inner object is destroyed when function come to the "return" statement. Is default copy contructor doing some job? Can somebody explain me what exactly is happening in the following code when it invoke boo myres=calculateSomething(12); #include <iostream> #include <cstdlib> #include <math.h>
49
2332
by: Luke Meyers | last post by:
Lately I find myself increasingly preferring the practice of going ever-so-slightly out of my way to avoid the use of the form of initialization which uses the '=' symbol, on the grounds that it can be mistaken too easily for assignment. I like the avoidance of mistakes. I like even more the frequent, subtle reinforcement (for myself and my colleagues) of the point that assignment and initialization are entirely different operations. ...
8
1881
by: kevin | last post by:
Hello! So I was reading O'Reilly's C++ in a Nutshell when I came accross something interesting: The class definition for basic_ostream contains numerous overloaded operator<< functions: template <class charT, class traits = char_traits<charT class basic_ostream : virtual public basic_ios<charT,traits>
0
9691
marktang
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...
0
9551
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10253
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9090
agi2029
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...
1
7580
isladogs
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...
0
6813
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
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
3
2945
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.