Why would a new of object be created without assigning it to any of variable?
new A;
???
tx 27 1956
ajay wrote: Why would a new of object be created without assigning it to any of variable?
new A;
??? tx
For side effects.
--
Regards,
Buster.
"Buster" <no***@nowhere.com> wrote in message
news:c5**********@newsg3.svr.pol.co.uk... Why would a new of object be created without assigning it to any of
variable? new A;
??? tx
For side effects.
It's a memory leak in C++.
> > > new A;
It's a memory leak in C++.
It is, but this could very well not be:
new A(b);
Corno
Siemel Naran wrote: "Buster" wrote
Why would a new of object be created without assigning it to any of variable?
new A;
??? tx
For side effects.
It's a memory leak in C++.
Not necessarily.
--
Regards,
Buster.
"Buster" <no***@nowhere.com> wrote in message
news:c5**********@newsg2.svr.pol.co.uk... Siemel Naran wrote: new A;
It's a memory leak in C++.
Not necessarily.
If you overload global operator new, etc?
"Corno" <Corno@dds%FAKE%.nl> wrote in message
news:c5*********@news.tudelft.nl... > new A; > It's a memory leak in C++.
It is, but this could very well not be:
new A(b);
Perhaps so. But we still ought not to be writing code like this in C++. OK
in Java and other garbage collected languages.
Siemel Naran wrote: "Buster" wroteSiemel Naran wrote:
> new A;
It's a memory leak in C++.
Not necessarily.
If you overload global operator new, etc?
Or if an exception will be thrown during construction.
--
Regards,
Buster.
* "Corno" <Corno@dds%FAKE%.nl> schriebt: > > new A; > It's a memory leak in C++.
It is, but this could very well not be:
new A(b);
There is nothing in the latter expression that makes it less likely
to be a memory leak.
Not that a new-expression by itself is _necessarily_ a leak.
But you have to use extremely contorted mechanisms to avoid a leak, and
in that case it's much easier to use e.g. 'std::auto_ptr<A>( new A );',
or, if class A does not depend on dynamic allocation, simply 'A();'.
--
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Corno wrote: new A;
It's a memory leak in C++.
It is, but this could very well not be:
new A(b);
Do you mean "new (b) A;"?
--
Regards,
Buster.
ajay wrote: Why would a new of object be created without assigning it to any of variable?
new A;
It wouldn't, in my code.
One exception -- placement new:
new (some_address) A;
No need to save the address in this case, because you already know it.
-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Le mardi 13 avril 2004 à 09:05, Siemel Naran a écrit dans
comp.lang.c++*: >new A; It's a memory leak in C++.
Not necessarily.
If you overload global operator new, etc?
"A" could be a singleton class with a static member to store the address
of the constructed instance. Something like this:
// Untested code below
class A
{
private:
static A *pA;
public:
A()
{
if (NULL == pA)
{
pA = this;
}
// (re)set pA->members...
}
~A()
{
if (this == pA)
{
// clean pA->members...
pA = NULL;
}
}
A *instance()
{
return pA;
}
};
A *A::pA = NULL;
int main()
{
new A;
// do stuff
delete A::instance();
return 0;
}
--
___________ 2004-04-13 10:36:56
_/ _ \_`_`_`_) Serge PACCALIN -- sp ad mailclub.net
\ \_L_) Il faut donc que les hommes commencent
-'(__) par n'être pas fanatiques pour mériter
_/___(_) la tolérance. -- Voltaire, 1763
"ajay" <my******@lucent.com> wrote in message
news:40***************@lucent.com... Why would a new of object be created without assigning it to any of
variable? new A;
??? tx
I use it when adding items to a hashtable that I've made. The hastable
requires a class that inherits MyNullClass. To add to the hastable I use
this:
bool Put(int xiKey, MyNullClass *xiIn);
For storing a class of type FOO, then i use something like
class FooDataItem : public MyNullClass
{
public:
FooDataItem(Foo *xiIn){mFooItem = xiIn;}
virtual ~FooDataItem(){}
protected:
Foo *mFooItem;
};
Now, when I add an item to the HT, I dont want to store the FooDataItem, so
I add like this:
int key;
Foo *ABC;
// allocate mem and do some stuff with foo
MyHt->Put(key, new FooDataItem(ABC));
The last line calls new but doesnt assign it to any variable (it actually
doeswithin the hash table, but it doesnt appear to).
The line could be re-written as:
FooDataItem *lFDI = new FooDataItem(ABC);
MyHt->Put(key, lFDI);
Which is a bit messier in my opinion. I guess this comes from writing
programs in java.
HTH
Allan
Tx Serge,
ur answer seems to be reasonable.
In message <c5**********@newsg2.svr.pol.co.uk>, Buster
<no***@nowhere.com> writes Siemel Naran wrote: "Buster" wroteSiemel Naran wrote:
>> new A; It's a memory leak in C++.
Not necessarily. If you overload global operator new, etc?
Or if an exception will be thrown during construction.
Or if its constructor registers it with some other object which takes
responsibility for deleting it.
--
Richard Herring
Richard Herring wrote: In message <c5**********@newsg2.svr.pol.co.uk>, Buster <no***@nowhere.com> writes
Siemel Naran wrote:
"Buster" wrote
Siemel Naran wrote:
>>> new A; > > It's a memory leak in C++.
Not necessarily.
If you overload global operator new, etc?
Or if an exception will be thrown during construction. Or if its constructor registers it with some other object which takes responsibility for deleting it.
Or if it just needs to hang around until the program completes for some
reason.
On Tue, 13 Apr 2004 07:13:26 GMT, al***@start.no (Alf P. Steinbach) wrote: * "Corno" <Corno@dds%FAKE%.nl> schriebt: > > > > > > new A; > > > > It's a memory leak in C++. > It is, but this could very well not be:
new A(b);
There is nothing in the latter expression that makes it less likely to be a memory leak.
Not that a new-expression by itself is _necessarily_ a leak.
But you have to use extremely contorted mechanisms to avoid a leak, and in that case it's much easier to use e.g. 'std::auto_ptr<A>( new A );', or, if class A does not depend on dynamic allocation, simply 'A();'.
I've been trying to think of a way that any /statement/ of the form:
new A(anything-or-nothing);
(that would include /both/ Siemel and Corno's examples) would not be a leak
(assuming it doesn't fail or somehow get optimized away), and haven't been
able to. Note that in these cases, the expression stands alone as an
expression statement; there's no additional chicanery. And note also that
this does not contradict what you said above; I'm just contrasting your
comments with the language of the OP and those early responses in order to
try to plug a possible point of confusion.
Even if class A has no base classes or non-static data, aren't objects
obliged to have size >= 1? So no matter what you do, isn't at least that
one byte going to hanging over you up to program termination?
Consider this program (output follows, showing results of the assigned
"new" operations with and without the commented out raw "new" in between
them):
#include <iostream>
using namespace std;
class A {};
int main()
{
cout << "Without a new in between: " << endl;
A *p1 = new A();
// new A();
A *p2 = new A();
cout << "p1's at: " << p1 << ", and p2's at: " << p2 << endl;
return 0;
}
d:\src\learn>size
With a new in between:
p1's at: 3293648, and p2's at: 3293696
d:\src\learn>size
Without a new in between:
p1's at: 3293648, and p2's at: 3293672
Of course there are no "guarantees" about where memory comes from and in
what order using "new", but I think this illustrates the point.
-leor
--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at: www.bdsoft.com/tools/stlfilt.html
* Leor Zolman <le**@bdsoft.com> schriebt: On Tue, 13 Apr 2004 07:13:26 GMT, al***@start.no (Alf P. Steinbach) wrote:
* "Corno" <Corno@dds%FAKE%.nl> schriebt: > > > > > > new A; > > > > It's a memory leak in C++. > It is, but this could very well not be:
new A(b); There is nothing in the latter expression that makes it less likely to be a memory leak.
Not that a new-expression by itself is _necessarily_ a leak.
But you have to use extremely contorted mechanisms to avoid a leak, and in that case it's much easier to use e.g. 'std::auto_ptr<A>( new A );', or, if class A does not depend on dynamic allocation, simply 'A();'.
I've been trying to think of a way that any /statement/ of the form:
new A(anything-or-nothing);
(that would include /both/ Siemel and Corno's examples) would not be a leak (assuming it doesn't fail or somehow get optimized away), and haven't been able to.
Well the simplest one has already been mentioned by others: if A::A() throws.
But that wasn't what I meant by contorted.
Here's a contorted scheme:
class A;
class Cleanup
{
public:
~Cleanup(){ set( 0 ); }
static void set( A* pObj ){ delete myP; myP = pObj; }
private:
static A* myP;
};
A* Cleanup::myP = 0;
class A
{
public:
A(){ Cleanup::set( this ); }
};
int main()
{
Cleanup aCleaner;
new A;
}
Here class Cleanup could conceivably be one of those dreaded "Manager"
singleton classes or some such, where objects install themselves --
which I think is very bad design, but it happens.
Note that in these cases, the expression stands alone as an expression statement; there's no additional chicanery.
What I meant by extremely contorted mechanism was chicanery like the
above.
And note also that this does not contradict what you said above; I'm just contrasting your comments with the language of the OP and those early responses in order to try to plug a possible point of confusion.
Heh. I'm often wrong. I like to boast that I'm wrong in less than 50% of
cases, but.
Even if class A has no base classes or non-static data, aren't objects obliged to have size >= 1? So no matter what you do, isn't at least that one byte going to hanging over you up to program termination?
If there is no cleanup mechanism, yes, in the sense that one address from
the address space continues to be reserved. Not necessarily in the sense
that that address could have been used for a non-zero size object. But I
think that amounts to the same thing.
--
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
On Tue, 13 Apr 2004 13:11:50 +0000, Leor Zolman wrote: I've been trying to think of a way that any /statement/ of the form:
new A(anything-or-nothing);
would not be a leak
The constructor of A _may_ store the address of the new object somewhere
for later deletion. But in that case I would write the code as:
new A; /* Not a leak, A's constructor registers the address with <xyz> so
it will be deleted automatically when <zxy> */
Atleast if someone else migt look at (or maintain) the code.
Wether doing this is good design is a different debate. (My answer would
be, "it depends")
--
NPV
"the large print giveth, and the small print taketh away"
Tom Waits - Step right up
On Tue, 13 Apr 2004 13:29:59 GMT, al***@start.no (Alf P. Steinbach) wrote: I've been trying to think of a way that any /statement/ of the form:
new A(anything-or-nothing);
(that would include /both/ Siemel and Corno's examples) would not be a leak (assuming it doesn't fail or somehow get optimized away), and haven't been able to. Well the simplest one has already been mentioned by others: if A::A() throws.
Well, that's kinda what I meant by "doesn't fail" above ;-) But that wasn't what I meant by contorted.
Here's a contorted scheme:
[ not-that-unreasonable-of-a-contorted-scheme snipped ]
Oh yeah, that's kinda cool actually... Here class Cleanup could conceivably be one of those dreaded "Manager" singleton classes or some such, where objects install themselves -- which I think is very bad design, but it happens.
Okay, perhaps /not/ so cool...
Note that in these cases, the expression stands alone as an expression statement; there's no additional chicanery.
Right you are. What I meant by extremely contorted mechanism was chicanery like the above.
And note also that this does not contradict what you said above; I'm just contrasting your comments with the language of the OP and those early responses in order to try to plug a possible point of confusion.
Heh. I'm often wrong. I like to boast that I'm wrong in less than 50% of cases, but.
Even if class A has no base classes or non-static data, aren't objects obliged to have size >= 1? So no matter what you do, isn't at least that one byte going to hanging over you up to program termination?
If there is no cleanup mechanism, yes, in the sense that one address from the address space continues to be reserved. Not necessarily in the sense that that address could have been used for a non-zero size object. But I think that amounts to the same thing.
Not sure what you're trying to say exactly in those last two sentences, but
I'm not particularly worried about it. Thanks for the insight,
-leor
--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at: www.bdsoft.com/tools/stlfilt.html
"ajay" <my******@lucent.com> wrote in message
news:40***************@lucent.com... Why would a new of object be created without assigning it to any of
variable? new A;
Microsoft MFC uses this approach, as does many of the myriad of controls on
sites like codeguru and code project. The resultant lack of clearly
specified ownership IMO, contributes to many of the difficulties in
implementing MFC apps.
Jeff F
ajay <my******@lucent.com> wrote in message news:<40***************@lucent.com>... Why would a new of object be created without assigning it to any of variable?
new A;
You see something similar in a lot of code built on the Qt and KDE
frameworks, because the frameworks themselves provide a replacement
for language facilities such as RTTI and object lifetime control. You
will see code such as
new QListItem(this, "data");
which dynamically creates a QListItem object and adds it to "this,"
which is a QList object and will delete the QListItem at the
appropriate time.
It is not a memory leak, but it takes a lot of self-control to use
since it requires a slightly different mindset than conventional
idiomatic C++ use.
--
Stephen M. Webb st**********@bregmasoft.com
"Siemel Naran" <Si*********@REMOVE.att.net> wrote "Buster" <no***@nowhere.com> wrote
Why would a new of object be created without assigning it to any of variable?
new A;
??? tx
For side effects.
It's a memory leak in C++.
That's a premature assumption. The object could delete itself after doing
something or it might register itself with an object manager or an event
dispatcher (and later receive a 'delete self' event). Or it may not be
intended to be deleted. Objects that are meant to live until the expiration
of the program are not considered to be a memory leak.
Claudio Puviani
Bill Seurer wrote: Or if it just needs to hang around until the program completes for some reason.
In that case, don't do it this way. It's best to never write code that
relies on the environment to clean up after your program terminates, for
a number of reasons. Not all environments do clean-up (in a reasonable
way), objects don't get destructed, you may have problems later when
your program becomes a subroutine of a larger system, etc.
If you want the object to live until the end of the program, there are a
number of possible schemes. For example, just make it an auto object in
main(), or a global object. Or a static object in a function, which
allows you more control over when it is created.
-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
On Tue, 13 Apr 2004 18:50:38 +0000, Kevin Goodsell wrote: Bill Seurer wrote:
Or if it just needs to hang around until the program completes for some reason.
In that case, don't do it this way. It's best to never write code that relies on the environment to clean up after your program terminates, for a number of reasons. Not all environments do clean-up (in a reasonable way), objects don't get destructed, you may have problems later when your program becomes a subroutine of a larger system, etc.
Not to mention that it clutters up the logs horribly if you're searching
for any other (unintentional) leak.
--
NPV
What did that old blonde gal say? -- That is the part you throw away.
Tom Waits - The part you throw away
"Allan Bruce" <al*****@TAKEAWAYf2s.com> wrote in message
news:c5**********@news.freedom2surf.net... I use it when adding items to a hashtable that I've made. The hastable requires a class that inherits MyNullClass. To add to the hastable I use this:
MyHt->Put(key, new FooDataItem(ABC));
The last line calls new but doesnt assign it to any variable (it actually doeswithin the hash table, but it doesnt appear to).
Yes, this is perfectly valid. The original post seems to be about "new
X();" without anything else. In general, it looks like a memory leak, but
as others point it need not be, as when you overload X::operator new or
operator new, or in the constructor of X store the address of X somewhere.
And of course, the original code may have been a typo for placement new.
FooDataItem *lFDI = new FooDataItem(ABC); MyHt->Put(key, lFDI);
Which is a bit messier in my opinion. I guess this comes from writing programs in java.
Second way is safer in general as (but you also have to use smart pointers),
but either is fine for your specific example. In the expression Put(key(),
new Foo()) the compiler may evaluate the new Foo() first and suppose that
works, then it will evaluate key() and suppose that throws an exception,
then the new Foo is never deleted. So the safe way is
std::auto_ptr<FooDataItem> lFDI ( new FooDataItem(ABC) );
MyHt->Put(key, lFDI);
and the Put function receives an auto_ptr. The use of auto_ptr or any smart
pointer in the signature of Put implies that Put takes ownership of the
object, which is good documentation. st**********@bregmasoft.com (Stephen M. Webb) wrote in message news:<34**************************@posting.google. com>... ajay <my******@lucent.com> wrote in message news:<40***************@lucent.com>... Why would a new of object be created without assigning it to any of variable?
new A;
You see something similar in a lot of code built on the Qt and KDE frameworks, because the frameworks themselves provide a replacement for language facilities such as RTTI and object lifetime control. You will see code such as
new QListItem(this, "data");
which dynamically creates a QListItem object and adds it to "this," which is a QList object and will delete the QListItem at the appropriate time.
It is not a memory leak, but it takes a lot of self-control to use since it requires a slightly different mindset than conventional idiomatic C++ use.
QList is a display widget, by the way, not a container like std::list.
Another example would be
new QMessageBox( arguments..., parent_window, ... ,
Qt::WDestructiveClose );
The reason is that in a GUI, lifetime is somewhat complicated. For
instance, the QMessageBox needs to be deleted when the OK button is
pressed, but also when the parent_window is closed. The
parent_window must somehow know whether it has a QMessageBox child.
Qt will handle this memory management for you if you use its
ownership model. A typical dialog constructor will create the layout
by creating a number of widgets, and simply throw away the return
value of the new's of all fixed widgets (e.g. labels, lines).
Regards,
Michiel Salters
Kevin Goodsell wrote: Bill Seurer wrote:
Or if it just needs to hang around until the program completes for some reason.
In that case, don't do it this way. ...
I agree. But back to the start of this subthread it's not necessarily a
memory leak. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Daniel |
last post by:
Hello =)
I have an object which contains a method that should execute every x ms. I
can use setInterval inside the object construct like this -
self.setInterval('ObjectName.methodName()',...
|
by: Mark D. Anderson |
last post by:
About a month ago Richard Cornford did an interesting analysis of a
memory leak
in jscript (internet explorer) when there are "circular" references
between
DOM objects and (real) jscript objects:...
|
by: vanGogh |
last post by:
I have generated classes based on an Xml schema file (xsd) using the XSD.exe tool.
My goal is to:
- write an application that can parse XML documents
- fill objects (based on the generated...
|
by: ajay |
last post by:
Why would a new of object be created without assigning it to any of variable?
new A;
???
tx
|
by: Martin |
last post by:
I'd like to be able to get the name of an object instance from within
a call to a method of that same object. Is this at all possible?
The example below works by passing in the name of the object...
| |
by: sneill |
last post by:
How is it possible to take the value of a variable (in this case,
MODE_CREATE, MODE_UPDATE, etc) and use that as an object property name?
In the following example I want 'oIcon' object to have...
|
by: Lee Jackson |
last post by:
Whats the difference between the following in terms of how the CLR
allocates and garbage collects? Which is better in terms of memory
usage/performance?
a)
foreach (string strURL in...
|
by: Roman Ziak |
last post by:
Hello,
there were times when I used to be looking for a way to access
JavaScript Global object similar to those found in VBScript or PHP
($GLOBALS). At present this has only academic value for...
|
by: Shailen Sukul |
last post by:
Observed a weird behaviour with object references.
See code listing below:
using System;
using System.Collections.Generic;
using System.Text;
namespace PointerExceptionTest
{
/*
|
by: Astley Le Jasper |
last post by:
Sorry for the numpty question ...
How do you find the reference name of an object?
So if i have this
bob = modulename.objectname()
how do i find that the name is 'bob'
|
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,...
| |
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...
|
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...
|
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,...
|
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...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The...
|
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 ...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |