Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

when to use "new"

1 view
Skip to first unread message

Rv5

unread,
Nov 15, 2004, 1:36:13 AM11/15/04
to
Rookie c++ question, but Ive spent the last 5 years doing Java, where
everytime I created an object I used new. In c++ I can create my objects
without and its confusing me just a little.

I have a class called polynomial. Its a nothing little class right now,
with just int variables, a basic container class. Im using it as I go
through some tutorials, but in this particular tutorial its telling me to do
polynomial *first = new polynomial();
but before I found this site I was just doing
polynomial first;
Im also struggling through pointers. I understand the basics, but fail to
see the advantage using them with my objects so quickly. Is one way better
than the other?

Thanks


Ivan Vecerina

unread,
Nov 15, 2004, 1:58:40 AM11/15/04
to
"Rv5" <rmo...@adelphia.net> wrote in message
news:6aSdnVDuQIn...@adelphia.com...

> Rookie c++ question, but Ive spent the last 5 years doing Java, where
> everytime I created an object I used new. In c++ I can create my objects
> without and its confusing me just a little.
>
> I have a class called polynomial. Its a nothing little class right now,
> with just int variables, a basic container class. Im using it as I go
> through some tutorials, but in this particular tutorial its telling me to
> do
> polynomial *first = new polynomial();
This seems likely to be a poor advice...

> but before I found this site I was just doing
> polynomial first;
Right.

> Im also struggling through pointers. I understand the basics, but fail to
> see the advantage using them with my objects so quickly. Is one way
> better than the other?

In C++, most types should be value types, behaving and used like 'int'.

Instances only should be allocated with new when they can't or shouldn't
be copied, when an object instance needs to be shared/accessed from
multiple locations, or when the lifetime of the object needs to be
explicitly controlled.

Don't use 'new' until you find out that you have to.


I hope this helps,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com


John Harrison

unread,
Nov 15, 2004, 2:37:34 AM11/15/04
to

"Rv5" <rmo...@adelphia.net> wrote in message
news:6aSdnVDuQIn...@adelphia.com...
> Rookie c++ question, but Ive spent the last 5 years doing Java, where
> everytime I created an object I used new. In c++ I can create my objects
> without and its confusing me just a little.
>
> I have a class called polynomial. Its a nothing little class right now,
> with just int variables, a basic container class. Im using it as I go
> through some tutorials, but in this particular tutorial its telling me to
> do
> polynomial *first = new polynomial();
> but before I found this site I was just doing
> polynomial first;

It's likely that you are right and the tutorial is wrong. If it works
without new then don't use it. Avoiding new leads to clearer code (because
the lifetime of the object is limited) and more efficient code (for the same
reason). Occaisionally you see code like this

{
Wotsit* w = new Wotsit();
...
delete w;
}

That's clearly rubbish because the object lifetime is exactly the same as if
w was an automatic variable.

{
Wotsit w;
...
}

The second version is exception safe too.

> Im also struggling through pointers. I understand the basics, but fail to
> see the advantage using them with my objects so quickly. Is one way
> better than the other?

Same advice again, if you don't see the need for pointers don't use them.
They are tricky to use correctly so avoid them if you can. But I find it
surprising that you don't see the need if you have been programming Java, in
Java almost everything is a pointer.

john


Sam

unread,
Nov 15, 2004, 3:10:18 AM11/15/04
to
Maybe you should understand what the stack is and what the heap is.
The memory for a local variable in a function (or a method of a class) is in
the stack. When the function runs, the memory for local variables are
allocated in a special memory area called the stack. Once the function
returns, the memory allocated for its local variables is free immediately
and all the values of its local variables are lost. An instance of a class
constructed in this way acts exactly like an ordinary variable such as int,
float, etc.
Now we get a problem. You can write the following Java codes:
Polynomial createNew() {
return new Polynomial();
}
the function creates a new instance of class Plynomial and returns the
reference of that new instance.

But in C++, if you write
Polynomial* createNew() {
Polynomial pn;
return &pn;
}

It doesn't work. It may be compiled and linked but actually it's very
dangerous. The instance of Polynomial is constructed when the function is
called, but also is destroyed as soon as the function returns. However, the
caller gets the pointer of that nonexistent object returned by the function
and takes it as a valid pointer.

We want a way to create new objects other than in the stack, so that we can
hold the objects even if the functions that create them return. So we get
heap. We use "new expression" to create new objects in the heap - another
special memory area where objects created by "new expressions" exist. Thus
we can write the following codes in C++:
Polynomial* createNew() {
Polynomial* ppn = new Polynomial;
return ppn;
}
Memory allocated by "new expressions" can and only can be freed by "delete"
in the C++ codes. So here comes another thing: delete anything you created
by new (after they are useless, but before you lose the pointers of them).
Unlike in Java, the system doesn't clear the useless objects created by new
here.

"Rv5" <rmo...@adelphia.net> 写入消息新闻:6aSdnVDuQIn...@adelphia.com...

Rv5

unread,
Nov 15, 2004, 3:15:59 AM11/15/04
to
I admit that with java I didnt really think of pointers that much, even
though I knew they were being used behind the scenes. I do see the value in
them, but it seems to me that they get used a lot when it isnt necessary.

That said, and back to a spin off of my original question, if I do need just
a pointer to an object and not an object itself, would i use "new" in that
case? For example:
myobject *pointer = new myobject

Just trying to figure out possible scenarios.

ross

Ivan Vecerina

unread,
Nov 15, 2004, 3:41:36 AM11/15/04
to
"Rv5" <rmo...@adelphia.net> wrote in message
news:fOKdnSkCTrd...@adelphia.com...

> That said, and back to a spin off of my original question, if I do need
> just a pointer to an object and not an object itself, would i use "new" in
> that case? For example:
> myobject *pointer = new myobject

No, again, unless you need the lifetime of the object to extend
the current function scope.
What you would write instead is:
myobject obj;
myobject* pointer = &obj;
But I do not see in what scenario you would want to do that.

When the ownership( = responsibility to destroy) of the object
is passed to another function, it is usually better to use
a smart pointer, such as std::auto_ptr.

Also, in many uses of pointers, in C++ it is better to use
references instead (e.g. as function parameters...).


hth

Gernot Frisch

unread,
Nov 15, 2004, 4:14:15 AM11/15/04
to
<snip>

> Now we get a problem. You can write the following Java codes:
> Polynomial createNew() {
> return new Polynomial();
> }
<snap>

Why does one want to do this:

Polynomial* p1 = OtherPoly.createNew();

instead of:
Polynomial p1 = OtherPoly;
??
I've never programmed much Java so I don't get the idea here. I think
you don't have to new/delete at all if you're from java world. If you
use container classes you have all the java functionality without
caring about new/delete. Correct me if I'm wrong.

-Gernot

Jason Heyes

unread,
Nov 15, 2004, 4:43:59 AM11/15/04
to
"Rv5" <rmo...@adelphia.net> wrote in message
news:6aSdnVDuQIn...@adelphia.com...

Declaring pointers all over the place is no way to write C++. Only use a
pointer when you need to control the lifetime of an object.


John Harrison

unread,
Nov 15, 2004, 5:30:29 AM11/15/04
to

"Rv5" <rmo...@adelphia.net> wrote in message
news:fOKdnSkCTrd...@adelphia.com...

>I admit that with java I didnt really think of pointers that much, even
>though I knew they were being used behind the scenes. I do see the value
>in them, but it seems to me that they get used a lot when it isnt
>necessary.
>
> That said, and back to a spin off of my original question, if I do need
> just a pointer to an object and not an object itself, would i use "new" in
> that case? For example:
> myobject *pointer = new myobject
>
> Just trying to figure out possible scenarios.
>
> ross
>

No, this is the common mistake. New is about the *lifetime* of the object
being created. An object created with new lives until you call delete,
that's what makes objects create with new different from automatic objects,
not pointers.

You can get a pointer to any object. If you want a pointer to an automatic
object use the & operator.

john


Sam

unread,
Nov 15, 2004, 5:51:59 AM11/15/04
to

"Gernot Frisch" <M...@Privacy.net> 写入消息新闻:2vra85F...@uni-berlin.de...

> <snip>
>> Now we get a problem. You can write the following Java codes:
>> Polynomial createNew() {
>> return new Polynomial();
>> }
> <snap>
>
> Why does one want to do this:
>
> Polynomial* p1 = OtherPoly.createNew();
>
> instead of:
> Polynomial p1 = OtherPoly;

I didn't mean that createNew() is a method of class Polynomial. However, no
matter whether it is or not. It's not my point. I was just saying that, you
can easily create a new object in a function in Java and return its
handle(or reference, or pointer) to the caller so that the caller can
control that object(by calling its method). But in C++, you can't do this
easily because the object you create within a function as a local variable
is destroyed automatically after the function returns. Thus the pointer it
returns doesn't point to a valid object any longer. So you have to use the
new expression if you want an object to exist after the function that
creates it returns.
For example, suppose you have another class called MySystem, you do this in
Java:
MySystem sys = new MySystem();
Polynomial poly = sys.createNew();
It works if you have the method createNew() in class MySystem:


Polynomial createNew() {
return new Polynomial();
}

But in C++, if you write:
MySystem sys;
Polynomial* p = sys.createNew();

you must have the mothod createNew() in class MySystem as follows
Polynomial* MySystem::createNew()
{
return new Polynomial;
}

rather than
Polynomial* MySystem::createNew()
{
Polynomial po;
return &po; // oops! a bad-point-to-be

Gernot Frisch

unread,
Nov 15, 2004, 6:07:51 AM11/15/04
to

"Sam" <mans...@hotmail.com> schrieb im Newsbeitrag
news:cna24c$566$1...@kermit.esat.net...

In C++ I'd write:

MySystem sys;
Polynomial poly; sys.CreateNew(poly); // Just set initial values

See - no new/delete required.
Avoid it where you can. It's more time efficient and if you come from
Java you don't get into memory leak trouble.

Just my .02$,
-Gernot

John Harrison

unread,
Nov 15, 2004, 6:29:17 AM11/15/04
to

"Sam" <mans...@hotmail.com> wrote in message
news:cna24c$566$1...@kermit.esat.net...

But you can simply write

Polynomial MySystem::createNew()
{
Polynomial po;
return po;
}

There is no need for pointers with all the trouble that they bring. If you
are worried about the cost of copying a Polynomial object then the answer is
to make that class efficiently copyable (by using smart pointers for
instance) not to avoid copying by introducing pointers.

john

Sam

unread,
Nov 15, 2004, 9:25:51 AM11/15/04
to
> In C++ I'd write:
>
> MySystem sys;
> Polynomial poly; sys.CreateNew(poly); // Just set initial values
It's just an example showing some differences between Java and C++. Actually
You cannot always avoid pointers in C++. Polynomial may be an abstract base
class here if I write a createNew() method for it. If I wanna just set
initial values, I should call it initPoly() something. And it is probable
that I wanna keep holding that new object after the function calling
createNew() returns.

Sam

unread,
Nov 15, 2004, 9:35:59 AM11/15/04
to
> But you can simply write
>
> Polynomial MySystem::createNew()
> {
> Polynomial po;
> return po;
> }
>
> There is no need for pointers with all the trouble that they bring. If you
> are worried about the cost of copying a Polynomial object then the answer
> is to make that class efficiently copyable (by using smart pointers for
> instance) not to avoid copying by introducing pointers.
>
> john
>
>
>
Yes. You're right. But may I argue that you need pointers for polymorphism
at least. "References" in c++ are more confused than pointers, I think.


Howard

unread,
Nov 15, 2004, 10:37:35 AM11/15/04
to

"John Harrison" <john_an...@hotmail.com> wrote in message
news:2vr4lpF...@uni-berlin.de...

>
> "Rv5" <rmo...@adelphia.net> wrote in message
> news:6aSdnVDuQIn...@adelphia.com...
>> Rookie c++ question, but Ive spent the last 5 years doing Java, where
>> everytime I created an object I used new. In c++ I can create my objects
>> without and its confusing me just a little.
>>
>> I have a class called polynomial. Its a nothing little class right now,
>> with just int variables, a basic container class. Im using it as I go
>> through some tutorials, but in this particular tutorial its telling me to
>> do
>> polynomial *first = new polynomial();
>> but before I found this site I was just doing
>> polynomial first;
>
> It's likely that you are right and the tutorial is wrong.


Hello...? Did it occur to you that the purpose of that particular tutorial
might be to *teach* using pointers? One does not learn how to use pointers
by avoiding them.

Pointers are useful in many situations, but they are most often useful when
storing polymorphic objects in containers. That is, storing pointers to
base class objects in a vector (for example), when those pointers actually
point to dynamically created instances of derived class objects. Of course,
that's something you wouldn't tackle until later, if you're just starting on
pointers, but it's an example of where they are commonly used.

All that said, I do agree that if you don't actually *need* pointers, don't
bother using them. You'll find out soon enough if there's a case where you
*do* need a pointer. (And just because a function you're calling requires a
pointer as a parameter, doesn't mean that you have to pass it a pointer
variable...you more likely want to pass the address of an existing object.)

At some point, you'll also want to look at using "smart" pointers. They
really help make code better in those cases where you *do* need pointers.

-Howard

Gernot Frisch

unread,
Nov 15, 2004, 11:21:15 AM11/15/04
to
> At some point, you'll also want to look at using "smart" pointers.
> They really help make code better in those cases where you *do* need
> pointers.

...depending on what you call "better" code. But, I agree, there's
situations where smarties are more appropreate than simple pointers...
-Gernot


Rv5

unread,
Nov 15, 2004, 12:30:22 PM11/15/04
to
Thanks for all the info guys. Lot to absorb. Im going to have to read each
post carefully, maybe ever a couple times to really grab what is going on
here. C++ is definitely a lot more indepth then java is.

"Sam" <mans...@hotmail.com> wrote in message
news:cnaf8d$8sn$1...@kermit.esat.net...

Karl Heinz Buchegger

unread,
Nov 15, 2004, 12:59:32 PM11/15/04
to
Rv5 wrote:
>
> Thanks for all the info guys. Lot to absorb. Im going to have to read each
> post carefully, maybe ever a couple times to really grab what is going on
> here. C++ is definitely a lot more indepth then java is.

Honestly. Not a good idea.
A better idea is to get a book. There are so many pitfalls and
things to know in C++, that you can't discover them on your own
without major frustration.

--
Karl Heinz Buchegger
kbuc...@gascad.at

DaKoadMunky

unread,
Nov 15, 2004, 3:38:23 PM11/15/04
to
> Only use a
>pointer when you need to control the lifetime of an object.

What if the type of object to be created is not known until run-time?

What if the number of objects to be created is not known until run-time?

At the lowest level I believe the new operator would be required.

Of course at a higher level one could use abstractions to avoid having to
explicitly use new and delete.

Jason Heyes

unread,
Nov 15, 2004, 9:12:32 PM11/15/04
to
"DaKoadMunky" <dakoa...@aol.com> wrote in message
news:20041115153823...@mb-m11.aol.com...

>> Only use a
>>pointer when you need to control the lifetime of an object.
>
> What if the type of object to be created is not known until run-time?
>

Such an object has it's lifetime managed by the programmer. What's your
point?


DaKoadMunky

unread,
Nov 15, 2004, 9:48:56 PM11/15/04
to
>Such an object has it's lifetime managed by the programmer. What's your
>point?

I interpreted your statement to mean that one should *only* use new for the
purposes of managing an objects lifetime.

I suggest that another purpose for using new is to defer the decision as to
which type of object to create to run-time.

It is true that the object will have its lifetime managed by the programmer but
the responsibility for lifetime management might be a consequence rather than a
goal.

void DoSomething(const string& typeIndicator)
{
Base* base = SomeFactoryFunction(typeIndicator);

delete base;
}

In this case the lifetime of the object presumably created with new is
identical to that of a variable with automatic storage duration. The need to
explicitly manage the lifetime of the object seems to be a consequence that
resulted from the need to delay the decision as to which kind of object to
create until run-time.

My only point is that lifetime management in one case might be exactly what is
desired whereas in another case it might just be a "side-effect".

Jason Heyes

unread,
Nov 16, 2004, 1:29:57 AM11/16/04
to
"DaKoadMunky" <dakoa...@aol.com> wrote in message
news:20041115214856...@mb-m04.aol.com...

I'm afraid you've lost me. I need a practical example of how a pointer could
be used without making it necessary to manage an object's lifetime. Dynamic
typing does make it necessary so as an example it isn't good enough.


Michiel Salters

unread,
Nov 16, 2004, 7:22:08 AM11/16/04
to
dakoa...@aol.com (DaKoadMunky) wrote in message news:<20041115153823...@mb-m11.aol.com>...

> > Only use a
> >pointer when you need to control the lifetime of an object.
>
> What if the type of object to be created is not known until run-time?

True, you need a pointer or reference there. A reference is often
a solution if you need either one of N possible globals.

i.e.
base& get1() { static der1 r; return r; }
base& get2() { static der2 r; return r; }
base& the_chosen = runtime_cond() ? get1() : get2();

> What if the number of objects to be created is not known until run-time?

std::vector<type>, std::list<type>, std::deque<type>

> At the lowest level I believe the new operator would be required.

It's often used, including array new[], and placement new(here). But
the first example shows there are alternatives. And even where you
use new, it's bet used indirectly - e.g. as part of a std:: class.

BTW, even if you use new directly, avoid the need for a matching
delete. Use a smart pointer instead, e.g. boost::scoped_ptr.

Regards,
Michiel Salters

Richard Herring

unread,
Nov 18, 2004, 11:14:21 AM11/18/04
to
In message <41999e6d$0$25116$afc3...@news.optusnet.com.au>, Jason Heyes
<jason...@optusnet.com.au> writes

Easy. Make it point to something that's not on the heap.

class Base { /*...*/};
class D1: public Base{/*...*/};
class D2: public Base{/*...*/};
/* etc. */

void DoSomething(int typeIndicator)
{
D1 d1;
D2 d2;
/* etc. */
Base * p=0;
switch (typeIndicator)
{
case 1: p = &d1; break;
case 2: p = &d2; break;
/*...*/
}
assert(p);
p->doSomething();

// note the absence of "delete p;"
}


> Dynamic
>typing does make it necessary so as an example it isn't good enough.
>
>

--
Richard Herring

RCS

unread,
Nov 27, 2004, 8:56:14 PM11/27/04
to

> BTW, even if you use new directly, avoid the need for a matching
> delete. Use a smart pointer instead, e.g. boost::scoped_ptr.
>
> Regards,
> Michiel Salters

Or, roll your own smart pointer class, which is a trivial thing to do,
with the benefit of totally controlling what's in the smart ptr class
(behaivour, etc), and without the hassle of importing another library
into the already muddled mix of libraies one have to deal with.

RCS

0 new messages