473,387 Members | 1,863 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Always avoid "new"

Is it right thing to always avoid using "new" to create objects? What if
after starting the application, then decide which and how many objects to
create? (Seems like under such situation is there no other choice but using
"new")
Jul 22 '05 #1
30 3506
"seesaw" <se****@turboweb.com> wrote in message
news:ro*******************@bgtnsc05-news.ops.worldnet.att.net...
Is it right thing to always avoid using "new" to create objects? What if
after starting the application, then decide which and how many objects to
create? (Seems like under such situation is there no other choice but using "new")


I have never heared of such a thing. Making new object using new or malloc
is very common and I don't see why you shouldn't use them.
1)You can allocate much more space using new on the heap rather than on
stack.
2)You can allocate exactly how much you need(
example
You need to read alot of information into an array, the maximum number of
possible elements is let's say 1 000 000. So the user inputs the first
number which
is the number of elements and then you allocate the needed space. Don't
forget to delete afterwards. And 1 more thing I don't thing you could
allocate that much space on stack.
)
HTH

--
Frane Roje

Have a nice day

Remove (*dele*te) from email to reply
Jul 22 '05 #2

"seesaw" <se****@turboweb.com> wrote in message
news:ro*******************@bgtnsc05-news.ops.worldnet.att.net...
Is it right thing to always avoid using "new" to create objects? What if
after starting the application, then decide which and how many objects to
create? (Seems like under such situation is there no other choice but using "new")


If new was never to be used why would it have been added to the language?

That said newbies often do use new when they don't need to, which results in
more complex and often less efficient code. A good principle to follow is
don't use new unless you can't see any other way of doing something. The
situation you quote is one such example. Another is when you want the
created object to have an indefinite lifetime (i.e. you only want the object
to be destroyed when you explicitly delete it, not when you exit the scope
in which it was declared)

john
Jul 22 '05 #3
seesaw wrote:
Is it right thing to always avoid using "new" to create objects? What if
after starting the application, then decide which and how many objects to
create? (Seems like under such situation is there no other choice but using
"new")

It would make a worthy if you argue to use new or malloc. The biggest
difference is new calls the constructor of the object whereas malloc
does not ( good ol' C )- it just allocates memory , thatz abt it.
Now, one place where you can argue for / against new is something like here.

void myfun () {
int * a = new int;
*a = 45;
// Thatz it . I am not doing anything with this.
delete a;
// God !! Why did I allocate this on the heap now.
// I didn't pass the variable around , it is so small anyway.
// I could have done this on stack !!!
}
But as you would have discovered, this is more a pedagogical case than a
practical one.

Other than this case, I dont find anything wrong against new.

HTH.

- Karthik.
Jul 22 '05 #4
> Is it right thing to always avoid using "new" to create objects? What if
after starting the application, then decide which and how many objects to
create? (Seems like under such situation is there no other choice but using "new")


I do actually avoid "new" as much as possible. The reason is this: The
destructor and deallocator are not called automatically, so to prevent
memory leaks other methods are needed such as try, catch or destructors from
other objects.

Of course if I need a variable number of objects, then I use new and store
the objects in a vector and let the vector do the cleanup. Or in those cases
where I do not store the object(s) in a vector, I store them in some other
object and make that objects destructor ensure cleanup.

An additional advantage of allocating on the stack instead of the heap, is
that if you have tested your application and thereby verified that there is
enough space on the stack, then you can be sure that there will always be
enough space on the stack for your objects (unless you depend on recursion).
With the heap you can not be sure that there is enough space and you risk
exceptions on that account.

Niels Dybdahl
Jul 22 '05 #5
seesaw posted:
Is it right thing to always avoid using "new" to create objects? What
if after starting the application, then decide which and how many
objects to create? (Seems like under such situation is there no other
choice but using "new")


Am I the only one that thinks this is stupid?

It's like saying "Always avoid rollerblades". Why the hell would I be
wearing the rollerblades in anyway? I myself wear shoes 99.999999999% of the
time. There would be times when I _would_ wear rollerblades though, although
I'm not gonna have rollerblades on all day.
Jul 22 '05 #6
>Of course if I need a variable number of objects, then I use new and store
the objects in a vector and let the vector do the cleanup.


Are you saying that you allocate T objects with the new operator and then store
the resulting pointers in an std::vector<T*>?

If that is the case then you are probably not getting the cleanup you expect.
Please see http://www.cuj.com/documents/s=7990/cujcexp1910austern/.
Jul 22 '05 #7
"seesaw" <se****@turboweb.com> wrote in message
news:ro*******************@bgtnsc05-news.ops.worldnet.att.net...
Is it right thing to always avoid using "new" to create objects?
"Always" is a little strong, but in practice there are good reasons to avoid
using "new" for creating more than one object at a time.
What if after starting the application, then decide which and how many
objects to create? (Seems like under such situation is there no other
choice but using "new")


Use a vector. In other words, instead of

T* tp = new T[n];

(after which you have to remember to say "delete[] tp"), say

vector<T> tv(n);

after which the elements of tv will be destroyed automatically when tv goes
out of scope.

In addition to this property, vectors have the advantage that they are easy
to resize, and they also support an efficient append operation.
Jul 22 '05 #8
"John Harrison" <jo*************@hotmail.com> wrote in message
news:c6************@ID-196037.news.uni-berlin.de...
If new was never to be used why would it have been added to the language?


Never is too strong -- but in my opinion, the most important use of new
(aside from allocating single objects, which is essential for many forms of
object-oriented programming) is as an implementation vehicle for library
data structures.

Remember that the standard-library containers came along a number of years
after "new"; if they had existed earlier, it is entirely possible that "new"
would never have entered the language.
Jul 22 '05 #9
"seesaw" <se****@turboweb.com> wrote in message news:<ro*******************@bgtnsc05-news.ops.worldnet.att.net>...
Is it right thing to always avoid using "new" to create objects? What if
after starting the application, then decide which and how many objects to
create? (Seems like under such situation is there no other choice but using
"new")


I think you are saying the memory manager should be avoided. Which is
a good thing. Use the stack as much as possible. It makes your
programs much more robust and immune from most of C/C++s biggest
problems imho. Greatly reducing memory fragmentation, memory leaks,
and debugging time. However totally avoiding the memory manager is
often impossible.

Perhaps somebody will write a book on how to avoid the memory manager.
Giving lots of good finely tuned examples of how to take all common
patterns and move them to the stack...
Jul 22 '05 #10
seesaw wrote:
Is it right thing to always avoid using "new" to create objects?


Of course not. You shouldn't use new to allocate if you can do without
it though because you can avoid a whole class of memory errors.
Jul 22 '05 #11
"Andrew Koenig" <ar*@acm.org> wrote
"John Harrison" <jo*************@hotmail.com> wrote
If new was never to be used why would it have been added to the language?


Never is too strong -- but in my opinion, the most important use of new
(aside from allocating single objects, which is essential for many forms of
object-oriented programming) is as an implementation vehicle for library
data structures.

Remember that the standard-library containers came along a number of years
after "new"; if they had existed earlier, it is entirely possible that "new"
would never have entered the language.


And wouldn't _that_ have been a mistake! The standard containers are a great
facility to have, but I doubt you honestly think that they're sufficient for all
needs and that mechanisms to create alternatives would have been removed from the
language even had containers been present from day one. Even the addition of
reasonable smart pointers wouldn't obviate the need for manual dynamic allocation
in certain contexts.

Claudio Puviani
Jul 22 '05 #12
seesaw wrote:

Is it right thing to always avoid using "new" to create objects? What if
after starting the application, then decide which and how many objects to
create? (Seems like under such situation is there no other choice but using
"new")


I'd certainly agree that new C++ programmers use dynamic array-like
things too often, usually the fault of bad tutorials or instructors. So
I'd say to avoid new[] as much as possible, but not new.

Creating objects via new is of course very important in using
polymorphism and design patterns such as Abstract Factory.

Vectors of pointers allow polymorphic containers, but carry with them
the responsibility for cleaning up the allocated objects, unless a
third-party smart pointer system is used (not currently part of ISO
standard C++). When I do that, I use a wrapper class, which has as part
of its destructor routines to walk the container and deallocate the
individual pointers.


Brian Rodenborn
Jul 22 '05 #13
Claudio Puviani wrote in
news:HI**********************@news4.srv.hcvlny.cv. net in comp.lang.c++:
"Andrew Koenig" <ar*@acm.org> wrote
"John Harrison" <jo*************@hotmail.com> wrote
> If new was never to be used why would it have been added to the
> language?


Never is too strong -- but in my opinion, the most important use of
new (aside from allocating single objects, which is essential for
many forms of object-oriented programming) is as an implementation
vehicle for library data structures.

Remember that the standard-library containers came along a number of
years after "new"; if they had existed earlier, it is entirely
possible that "new" would never have entered the language.


And wouldn't _that_ have been a mistake! The standard containers are a
great facility to have, but I doubt you honestly think that they're
sufficient for all needs and that mechanisms to create alternatives
would have been removed from the language even had containers been
present from day one. Even the addition of reasonable smart pointers
wouldn't obviate the need for manual dynamic allocation in certain
contexts.


With template variadic arguments:

T *ptr = std::new< T >( /* whatever */ );

Even better:

std::smart_ptr< T > ptr = std::new< T >( /* whatever */ );

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #14
"Claudio Puviani" <pu*****@hotmail.com> wrote in message
news:HI**********************@news4.srv.hcvlny.cv. net...
Remember that the standard-library containers came along a number of years after "new"; if they had existed earlier, it is entirely possible that "new" would never have entered the language.
And wouldn't _that_ have been a mistake! The standard containers are a great facility to have, but I doubt you honestly think that they're sufficient for all needs and that mechanisms to create alternatives would have been removed from the language even had containers been present from day one.


Whether it would have been a mistake must surely depend on what facilities
were put in place instead for library implementations. My point is mostly
that the definition of "new" is fairly strongly connected to the nature of
the language at the time of its introduction.
Jul 22 '05 #15

"seesaw" <se****@turboweb.com> wrote in message
news:ro*******************@bgtnsc05-news.ops.worldnet.att.net...
Is it right thing to always avoid using "new" to create objects? What if
after starting the application, then decide which and how many objects to
create? (Seems like under such situation is there no other choice but using "new")


Of course you should use "new" if you need to wait until runtime to decide
which objects, and how many, to create.
Jul 22 '05 #16

"Niels Dybdahl" <nd*@fjern.detteesko-graphics.com> wrote in message
news:40*********************@dtext02.news.tele.dk. ..
Is it right thing to always avoid using "new" to create objects? What if
after starting the application, then decide which and how many objects to create? (Seems like under such situation is there no other choice but using
"new")


I do actually avoid "new" as much as possible. The reason is this: The
destructor and deallocator are not called automatically, so to prevent
memory leaks other methods are needed such as try, catch or destructors

from other objects.


Yes, that's fine. But the OP said "always avoid using" it.
Jul 22 '05 #17

"Andrew Koenig" <ar*@acm.org> wrote in message
news:Q1*******************@bgtnsc04-news.ops.worldnet.att.net...
"seesaw" <se****@turboweb.com> wrote in message
news:ro*******************@bgtnsc05-news.ops.worldnet.att.net...
Is it right thing to always avoid using "new" to create objects?
"Always" is a little strong, but in practice there are good reasons to

avoid using "new" for creating more than one object at a time.
What if after starting the application, then decide which and how many
objects to create? (Seems like under such situation is there no other
choice but using "new")


Use a vector.


But of course, if *you* were the one having to implement the vector, you'd
have to use new.
Jul 22 '05 #18
"jeffc" <no****@nowhere.com> wrote in message
news:40********@news1.prserv.net...
Use a vector.
But of course, if *you* were the one having to implement the vector, you'd
have to use new.


Not really; I'd use std::allocator instead, because it gives me
finer-grained control over construction and destruction than new does.
Jul 22 '05 #19
"seesaw" <se****@turboweb.com> wrote in message news:<ro*******************@bgtnsc05-news.ops.worldnet.att.net>...
Is it right thing to always avoid using "new" to create objects? What if
after starting the application, then decide which and how many objects to
create? (Seems like under such situation is there no other choice but using
"new")


Well, I would better say: Always avoid new[]. ;)
Jul 22 '05 #20
Default User wrote:
Creating objects via new is of course very important in using
polymorphism and design patterns such as Abstract Factory.


Something else that should *always* be avoided.

Jul 22 '05 #21
seesaw wrote:
Is it right thing to always avoid using "new" to create objects?
What if, after starting the application,
then decide which and how many objects to create?
(Seems like, under such situation,
there is no other choice but using "new")
The latest version of C specifies "variable length arrays".
It is possible -- perhaps probable -- that the new version of C++
will adopt variable length arrays as well.

Some C++ compiler already implement this as an extension:
cat main.cc #include <iostream>

int main(int argc, char* argv[]) {
if (1 < argc) {
const
size_t n = atoi(argv[1]);
int a[n];
for (size_t j = 0; j < n; ++j)
a[j] = j;
for (size_t j = 0; j < n; ++j)
std::cout << a[j] << " = a[" << j << "]" << std::endl;
}
return 0;
}
g++ -Wall -o main main.cc
./main 10

0 = a[0]
1 = a[1]
2 = a[2]
3 = a[3]
4 = a[4]
5 = a[5]
6 = a[6]
7 = a[7]
8 = a[8]
9 = a[9]

This will make it *much* easier to avoid using new
in the situation that you are concerned about.

Jul 22 '05 #22
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message news:<40**************@jpl.nasa.gov>...
Default User wrote:
Creating objects via new is of course very important in using
polymorphism and design patterns such as Abstract Factory.


Something else that should *always* be avoided.


Now that is a statement which is even less backed by facts.

An Abstract Factory makes perfect sense, if the design requires
creation of objects whose type is not statically known. There
are well-known implementation issues (e.g. should return smart
pointer) but when these issues are avoided AF is the best
solution for that specific problem.

Regards,
Michiel Salters
Jul 22 '05 #23
seesaw wrote:
Is it right thing to always avoid using "new" to create objects?
What if after starting the application, then decide which and how
many objects to create? (Seems like under such situation is there
no other choice but using "new")


No, this is certainly not right.

If you're not restricted by coding rules or other issues,
you should try to find the most appropriate approach which solves
your task.

Usually, the result depends on your experience, skill and often -
the striking thought which enlightens you....

If you end up with "new" being part of your solution, there's
nothing against it. It's part of the language, and it's there to be
used.

However, I'd advise you to handle it with care - nothing more.

If you make use of new (new[]), always check if the appropriate
delete(delete[]) operator is in place and works correctly.

Then check if you have implemented the correct means (pointers with
its necessary life-time) to keep control over the created objects.

And finally, have a close look to all sort of exceptions and
ill-conditions, which might confuse your usual program flow, so
that your deallocations don't fail.

Bernhard
Jul 22 '05 #24
"E. Robert Tisdale" wrote:

Default User wrote:
Creating objects via new is of course very important in using
polymorphism and design patterns such as Abstract Factory.


Something else that should *always* be avoided.


The usual worthless Trollsdale opinion.

Brian Rodenborn
Jul 22 '05 #25
Michiel Salters wrote:
E. Robert Tisdale wrote:
Default User wrote:
Creating objects via new is of course very important in using
polymorphism and design patterns such as Abstract Factory.
Something else that should *always* be avoided.


Now that is a statement which is even less backed by facts.

An Abstract Factory makes perfect sense,

if the design requires creation of objects
whose type is not statically known.
These are very rare and special circumstances.
Before you use an "abstract factory",
you need to show that these circumstances *cannot* be avoided.
Otherwise, you are simply building in a hazard for yourself
and other programmers who must maintain your code.
There are well-known implementation issues
(e.g. should return smart pointer)
but when these issues are avoided,
AF is the best solution for that specific problem.


Jul 22 '05 #26

"Andrew Koenig" <ar*@acm.org> wrote in message
news:5K********************@bgtnsc04-news.ops.worldnet.att.net...
"jeffc" <no****@nowhere.com> wrote in message
news:40********@news1.prserv.net...
Use a vector.
But of course, if *you* were the one having to implement the vector,

you'd have to use new.


Not really; I'd use std::allocator instead, because it gives me
finer-grained control over construction and destruction than new does.


OK you got me. But presumably you see my point anyway. The OP was asking
generically about new, and my point was there comes a time when you should
use it and need to know how to use it.
Jul 22 '05 #27
"tom_usenet" <to********@hotmail.com> wrote in message
news:q2********************************@4ax.com...
On Fri, 30 Apr 2004 15:58:31 GMT, "Claudio Puviani" new expressions are a bit odd - the array version calls the default
constructor, which is hardly helpful in general. You also have to
match your array and non-array versions. Seems like we could do
without it if we had another, more fundamental container type, like
"std::buffer" (with no capacity, just size). std::buffer could be used
to build std::vector!


What does std::allocator not do that you want?
Jul 22 '05 #28

seesaw wrote:
Is it right thing to always avoid using "new" to create objects? What if
after starting the application, then decide which and how many objects to
create? (Seems like under such situation is there no other choice but using
"new")


You know, i always tell myself not that i should avoid using new, but
that i should avoid using delete. i know that sounds flip, but i swear
by "smart" pointers of varying degrees of "smart"ness.

auto_ptr<Foo> bar1(new Foo());
//...
//no delete

boost::scoped_ptr<Foo> bar2(new Foo());
//...
//no delete

boost::shared_ptr<Foo> bar3(new Foo());
//...
//no delete

//and my own
dynamic_obj<Foo> bar4(new Foo());
//...
//on copy it allocates then copies
//...
//no delete

mark

Jul 22 '05 #29

Andrew Koenig wrote:
What does std::allocator not do that you want?


Anything useful. For what peeves me specifically, see 20.1.5 p4 & p5.

Also, the lack of some kind of standardized auto_allocator to complement
auto_ptr using a specific allocator is annoying some days. It would
really have been nice to have some version of new/delete that takes an
allocator type and instance in some kind of policy. These are just a few
geek fantasies i entertain when i'm retyping boilerplate.

mark
Jul 22 '05 #30
On Tue, 04 May 2004 18:29:37 GMT, "Andrew Koenig" <ar*@acm.org> wrote:
"tom_usenet" <to********@hotmail.com> wrote in message
news:q2********************************@4ax.com.. .
On Fri, 30 Apr 2004 15:58:31 GMT, "Claudio Puviani"

new expressions are a bit odd - the array version calls the default
constructor, which is hardly helpful in general. You also have to
match your array and non-array versions. Seems like we could do
without it if we had another, more fundamental container type, like
"std::buffer" (with no capacity, just size). std::buffer could be used
to build std::vector!


What does std::allocator not do that you want?


Apart from in-place expansion of memory (a la realloc)?

Well, it's lower level than what I'm suggesting, which fits in
somewhere between std::allocator and std::vector. It won't have a
capacity, but it will be copyable and exception safe. Alexandrescu
wrote about some kind of buffer class which is more what I'm thinking
of.
http://www.cuj.com/documents/s=7992/...r/alexandr.htm

Tom
--
C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #31

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Yi | last post by:
Hi, I am a scientist and new to .NET programming. On my PC, I am using Windows 2000 professional with IIS, SQL Server 2000 (standard, personal), Visual Basic .net (2003, standard). By following...
18
by: Leslaw Bieniasz | last post by:
Cracow, 28.10.2004 Hello, I have a program that intensively allocates and deletes lots of relatively small objects, using "new" operator. The objects themselves are composed of smaller...
24
by: Rv5 | last post by:
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...
4
by: Ben R. | last post by:
I'm curious about the differeng behavior of the "new" keyword when dealing with value versus object types. If I'm correct, when I do: dim x as integer There's no need for "new" to be called...
30
by: Medvedev | last post by:
i see serveral source codes , and i found they almost only use "new" and "delete" keywords to make they object. Why should i do that , and as i know the object is going to be destroy by itself at...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
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,...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.