By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,086 Members | 1,460 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,086 IT Pros & Developers. It's quick & easy.

new of an object without assigning it to any variable

P: n/a
Why would a new of object be created without assigning it to any of variable?

new A;

???
tx
Jul 22 '05 #1
Share this Question
Share on Google+
27 Replies


P: n/a
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.
Jul 22 '05 #2

P: n/a
"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++.
Jul 22 '05 #3

P: n/a
> > >
new A;

It's a memory leak in C++.

It is, but this could very well not be:

new A(b);

Corno
Jul 22 '05 #4

P: n/a
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.
Jul 22 '05 #5

P: n/a
"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?
Jul 22 '05 #6

P: n/a
"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.
Jul 22 '05 #7

P: n/a
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.

--
Regards,
Buster.
Jul 22 '05 #8

P: n/a
* "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?
Jul 22 '05 #9

P: n/a
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.
Jul 22 '05 #10

P: n/a
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.
Jul 22 '05 #11

P: n/a
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
Jul 22 '05 #12

P: n/a

"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
Jul 22 '05 #13

P: n/a
Tx Serge,
ur answer seems to be reasonable.
Jul 22 '05 #14

P: n/a
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.

--
Richard Herring
Jul 22 '05 #15

P: n/a
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.
Jul 22 '05 #16

P: n/a
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
Jul 22 '05 #17

P: n/a
* 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?
Jul 22 '05 #18

P: n/a
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

Jul 22 '05 #19

P: n/a
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
Jul 22 '05 #20

P: n/a

"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
Jul 22 '05 #21

P: n/a
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
Jul 22 '05 #22

P: n/a
"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
Jul 22 '05 #23

P: n/a
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.
Jul 22 '05 #24

P: n/a
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

Jul 22 '05 #25

P: n/a
"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.
Jul 22 '05 #26

P: n/a
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
Jul 22 '05 #27

P: n/a
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.
Jul 22 '05 #28

This discussion thread is closed

Replies have been disabled for this discussion.