When should use "new"?

G

garyolsen

For a class, MyClass, there are two ways to instantiate an object:

1. MyClass *MC = new MyClass();

2. MyClass MC;

In general, when should you have to use 1 and when 2? What're
advantages/disadvantages of using either?

Thanks!
 
R

Ron Natalie

garyolsen said:
For a class, MyClass, there are two ways to instantiate an object:

1. MyClass *MC = new MyClass();

2. MyClass MC;

In general, when should you have to use 1 and when 2? What're
advantages/disadvantages of using either?

Use #1 when #2 isn't enough.
 
M

Mike Wahler

garyolsen said:
For a class, MyClass, there are two ways to instantiate an object:

1. MyClass *MC = new MyClass();

2. MyClass MC;

In general, when should you have to use 1 and when 2?

In general, use the second form, use the first when you must.
What're
advantages/disadvantages of using either?

The only disadvantage I can think of for the second form
is that it might not be sufficient for a particular task.

A *possible* disadvantage of the first form is that it *might*
have poorer performance. Another is that it requires you to
remember to 'delete' it when done with it.

-Mike
 
G

garyolsen

Mike Wahler said:
In general, use the second form, use the first when you must.


The only disadvantage I can think of for the second form
is that it might not be sufficient for a particular task.

A *possible* disadvantage of the first form is that it *might*
have poorer performance. Another is that it requires you to
remember to 'delete' it when done with it.

-Mike
"poorer performance"? Why is that?
 
R

Ron Natalie

garyolsen said:
Would you mind to clarify a little bit about when #2 isn't enough? Thanks!

#2 can describe two different storage situations:
static storage duration or automatic. The main reason you end up
not being able to use automatic storage duration (local variables within a function)
is that they cease to be as soon as the block they are defined in is exitted, and this
may be before you are done with it in some designs.

Sometmes, you need to provide initializers on the fly which precludes using
static duration.
 
E

E. Robert Tisdale

garyolsen said:
For a class, MyClass, there are two ways to instantiate an object:
1. MyClass MC;

2. MyClass& MC = *(new MyClass());

3. MyClass *pMC = new MyClass();
In general, when should you have to use 1 and when 3?
What're advantages/disadvantages of using either?

*Never* create a pointer
unless you need to assign a different address to it later.
Use a reference instead.

*Never* allocate memory for an object from the free store (heap)
unless it must survive the scope of the allocation.

*Never* declare a variable unless you need to modify it later.
Use the const qualifier instead:

1. const MyClass MC;

2. const MyClass& MC = *(new MyClass());

3. const MyClass *pMC = new MyClass();
 
J

jeffc

garyolsen said:
For a class, MyClass, there are two ways to instantiate an object:

1. MyClass *MC = new MyClass();

2. MyClass MC;

In general, when should you have to use 1 and when 2?

Use 2 when you can. Use 1 if the situation forces you to. Let's say you
were creating a list of MyClass objects, but you don't know how many there
are going to be until the user gives you some input? Then you have to use
1. I think you're looking at it wrong. Don't think in terms of pointers
and new, think in terms of static and dynamic. Use static (2) whenever you
can - it's simpler. But when you can't - when you don't know until run time
if you'll need something, then that's called dynamic (1) allocation.
 
J

Jon Bell

Use 2 when you can. Use 1 if the situation forces you to. Let's say you
were creating a list of MyClass objects, but you don't know how many there
are going to be until the user gives you some input? Then you have to use
1.

Not necessarily. You can declare a vector<MyClass> to whatever size you
need, at run-time, and even re-size it if necessary. It uses pointers
behind the scenes, of course, but you don't have to worry about them. The
vector member functions take care of all the messy details.
 
M

Mike Wahler

garyolsen said:
"poorer performance"?

[of dynamic allocation vs static or auto objects]
Why is that?

There might be extra overhead involved for 'new' to do its
work. This is typically not noticable for a small number
of objects.

But as always, the only way to conclusively prove performance
(which can and does vary among platforms/implementations) is
to measure.

The main reason I advise using (if possible) static or auto
objects over dynamically allocated ones, is that if it's not
really needed, dynamic allocation will only unnecessarily
complicate the code, and introduce more possiblity for errors.

The less 'moving parts' the less possibility for failure, just
as with e.g. wristwatches, automobiles, etc. :)


-Mike
 
J

jeffc

Jon Bell said:
Not necessarily. You can declare a vector<MyClass> to whatever size you
need, at run-time, and even re-size it if necessary. It uses pointers
behind the scenes, of course...

But as I further explained, the OP should be thinking in terms of dynamic
vs. static. A vector is a dynamic data structure, and the person who coded
*that* had to use "new".
 
A

Andrey Tarasevich

garyolsen said:
For a class, MyClass, there are two ways to instantiate an object:

1. MyClass *MC = new MyClass();

2. MyClass MC;

In general, when should you have to use 1 and when 2? What're
advantages/disadvantages of using either?
...

Dynamic memory allocation (the first method) is usually used in the
following situations:

1. The type of the object referenced by a pointer (or a reference) is
not known at compile time (such as concrete size of an array or dynamic
type of a polymorphic object)

2. The total number of concrete objects of certain type is not known at
compile time (such as linked list nodes or tree nodes)

3. It is necessary to have an object who's lifetime is different from
the one imposed by static or automatic storage duration.

4. The object is to large to be placed in automatic or static memory.

In other cases (unless I missed something) there's no need to use
dynamic memory allocation.
 
A

Andrey Tarasevich

E. Robert Tisdale said:
...
*Never* allocate memory for an object from the free store (heap)
unless it must survive the scope of the allocation.

That's plain wrong. I might want to initialize a polymorphic base class
pointer to point to an instance of derived class (one of many possible
derived classes) even though the object won't survive the scope of the
allocation. That's a perfectly logical use of 'new'.

I might want to 'new' an array of objects, whose size is not known at
compile time, even though the array won't survive the scope of the
allocation.
*Never* declare a variable unless you need to modify it later.
Use the const qualifier instead:

1. const MyClass MC;

2. const MyClass& MC = *(new MyClass());

3. const MyClass *pMC = new MyClass();
...

These examples look kind of strange to me. How is it relevant? Did you
really intend to const-qualify the class instance and not the pointer?
 
E

Erik

For a class, MyClass, there are two ways to instantiate an object:
1. MyClass MC;

2. MyClass& MC = *(new MyClass());

3. MyClass *pMC = new MyClass();

*Never* create a pointer
unless you need to assign a different address to it later.
Use a reference instead.

*Never* allocate memory for an object from the free store (heap)
unless it must survive the scope of the allocation.

*Never* declare a variable unless you need to modify it later.
Use the const qualifier instead:

1. const MyClass MC;

2. const MyClass& MC = *(new MyClass());

*Never* do this!!!
If you do this, you will have a memory leak if you don't do "delete &MC",
which I doubt that you would.
Hardly readable in any case.
 
E

E. Robert Tisdale

Andrey said:
That's plain wrong.
I might want to initialize a polymorphic base class pointer
to point to an instance of derived class
(one of many possible derived classes)
even though the object won't survive the scope of the allocation.

Please show us an example.
That's a perfectly logical use of 'new'.

It isn't logical.
It isn't necessary to use 'new' to get a pointer to an object.
I might want to 'new' an array of objects
whose size is not known at compile time,
even though the array won't survive the scope of the allocation.


These examples look kind of strange to me. How is it relevant?
Did you really intend to const-qualify the class instance
and not the pointer?

Yes.
You may need to assign a different address
to a pointer to a const object.
 
C

Cy Edmunds

garyolsen said:
For a class, MyClass, there are two ways to instantiate an object:

1. MyClass *MC = new MyClass();

2. MyClass MC;

In general, when should you have to use 1 and when 2? What're
advantages/disadvantages of using either?

Thanks!


It seems that beginners (and expatriot Java programmers!) use #1 way too
much. It seems to be associated with the desire to do object oriented
programming. But now you have to manage the memory. If you forget to delete
it you have a memory leak and if you delete it twice you have undefined
behavior.

Another point about #1 is exception safety. For instance:

Fred *p = new Fred();
some_function(p);
delete p;

Looks ok, but if some_function throws, you have a memory leak. For this
reason it is common to use a smart pointer:

#include <memory>
std::auto_ptr<Fred> p(new Fred());
some_function(p.get());

The actual pointer is deleted automatically when p goes out of scope, so you
get no memory leak whether some_function throws or not.

Between smart pointers and standard collection classes, I find very little
reason to use delete or delete [], and I don't miss them a bit.
 
A

Andrey Tarasevich

E. Robert Tisdale said:
Please show us an example.
...


{
sorter* p_sorter =
b_use_bubble_sort ? new bubble_sorter : new quick_sorter;

p_sorter->sort(array1, n1);
p_sorter->sort(array2, n2);

delete p_sorter;
}

(The code is not exception safe, but that's irrelevant withing the
context of this discussion)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,148
Messages
2,570,838
Members
47,385
Latest member
Joneswilliam01

Latest Threads

Top