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

when to use "new"

P: n/a
Rv5
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
Jul 22 '05 #1
Share this Question
Share on Google+
24 Replies


P: n/a
"Rv5" <rm*****@adelphia.net> wrote in message
news:6a********************@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
Jul 22 '05 #2

P: n/a

"Rv5" <rm*****@adelphia.net> wrote in message
news:6a********************@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
Jul 22 '05 #3

P: n/a
Sam
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" <rm*****@adelphia.net> 写入消息新闻:6a********************@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;
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

Jul 22 '05 #4

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

Jul 22 '05 #5

P: n/a
"Rv5" <rm*****@adelphia.net> wrote in message
news:fO********************@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
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Jul 22 '05 #6

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

Jul 22 '05 #7

P: n/a
"Rv5" <rm*****@adelphia.net> wrote in message
news:6a********************@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;
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


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.
Jul 22 '05 #8

P: n/a

"Rv5" <rm*****@adelphia.net> wrote in message
news:fO********************@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
Jul 22 '05 #9

P: n/a
Sam

"Gernot Frisch" <Me@Privacy.net> 写入消息新闻:2v*************@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
}

??
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

Jul 22 '05 #10

P: n/a

"Sam" <ma*******@hotmail.com> schrieb im Newsbeitrag
news:cn**********@kermit.esat.net...

"Gernot Frisch" <Me@Privacy.net>
写入消息新闻:2v*************@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();
}


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

Jul 22 '05 #11

P: n/a

"Sam" <ma*******@hotmail.com> wrote in message
news:cn**********@kermit.esat.net...

"Gernot Frisch" <Me@Privacy.net>
写入消息新闻:2v*************@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
}


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

Jul 22 '05 #12

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

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


Jul 22 '05 #13

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

P: n/a

"John Harrison" <jo*************@hotmail.com> wrote in message
news:2v*************@uni-berlin.de...

"Rv5" <rm*****@adelphia.net> wrote in message
news:6a********************@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



Jul 22 '05 #15

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

P: n/a
Rv5
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" <ma*******@hotmail.com> wrote in message
news:cn**********@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

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.

Jul 22 '05 #17

P: n/a
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
kb******@gascad.at
Jul 22 '05 #18

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

P: n/a
"DaKoadMunky" <da*********@aol.com> wrote in message
news:20***************************@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?
Jul 22 '05 #20

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

P: n/a
"DaKoadMunky" <da*********@aol.com> wrote in message
news:20***************************@mb-m04.aol.com...
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".


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

P: n/a
da*********@aol.com (DaKoadMunky) wrote in message news:<20***************************@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
Jul 22 '05 #23

P: n/a
In message <41***********************@news.optusnet.com.au> , Jason Heyes
<ja********@optusnet.com.au> writes
"DaKoadMunky" <da*********@aol.com> wrote in message
news:20***************************@mb-m04.aol.com...
>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".


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.


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

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

This discussion thread is closed

Replies have been disabled for this discussion.