473,721 Members | 1,806 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pointer vs non-pointer

For pointer and non-pointer initialization of an object like

MyCar mycar;
MyCar* mycar = new MyCar();

I heard from other people saying if object i create must live outside
scape, then I use pointer version, else if only use object for a
limited scope, then use non-pointer version.

Does limited scope means the object is only used in the same function
like:
void myfunction(){
MyCar mycar;
// mycar is only used inside this function
}

and if mycar is used by outside scope means:
void myfunction(){
MyCar* mycar = new MyCar();
// mycar is used by other function also after function returns
mycar->AddEventListen er();
// even myfunction returns,
// but mycar still need to listen for events
}

I most case, I would perfer to use the static object creation:
MyCar mycar;
since I don't need to worry about delete / free object after creation.

When are the times I must use dynamic creation ( create a pointer )?
Jun 27 '08 #1
6 2522
Does limited scope means the object is only used in the same function

"Scope" generally means "within the inner-most open/close braces." For
example, in C++ you can even do things like:
void func(int x, int z)
{
if (x == 5)
{
int y = x + 1;
y *= z;
}

y += 14; // (Compile error because "y" is out of scope here!)
}
I most case, I would perfer to use the static object creation:
MyCar mycar;
since I don't need to worry about delete / free object after creation.

When are the times I must use dynamic creation ( create a pointer )?

One obvious case is when you actually want to create certain things
"dynamicall y." Suppose you're writing a game. When the user clicks the
mouse button, you want to make a gun fire a bullet. You don't know at
compile time how many times he might press that button. You would need
to create a new "MyBullet" object every time he presses the button, and
probably "delete" the objects when they hit something, or when they are
far enough away that you can't see them any more. You can't do that in
a clean way without creating the objects dynamically.

A common trick in the old days of C (and even before) was to place a
limit on the number of objects that could be created. That's the
reason, when you play "Galaga," that you can't fire more than two
bullets at a time. If you enforece a limit like this, then you can
declare your objects statically:

MyBullet bullets[2];

And then when the user presses the "fire" button, you have to check and
make sure that at least one of the bullets has already scrolled off the
top of the screen. If it has, you don't actually create anything, you
just move the bullet that's hiding just off the screen back to the tip
of the gun and start it going upward again.

There are certainly benefits to static allocation - speed being a major
one. There's also no possiblity of memory leaks. There are lots of
reasons to use dynamic allocation, but it's never absolutely necessary.
It just makes sense in a lot of cases. It's usually kind of a balancing
act.

Pat
Jun 27 '08 #2
On Tue, 22 Apr 2008 09:18:10 GMT, Your Name <no**@none.none wrote:
>
>Does limited scope means the object is only used in the same function


"Scope" generally means "within the inner-most open/close braces." For
example, in C++ you can even do things like:
void func(int x, int z)
{
if (x == 5)
{
int y = x + 1;
y *= z;
}

y += 14; // (Compile error because "y" is out of scope here!)
}

So, if I want to return an object created in a function I better use
dynamic creation?

MyCar myfunction(){
MyCar mycar;
return mycar;
} // this is return by value
// this is more expensive as it copy whole value and return value

MyCar* myfunction(){
MyCar* mycar = new MyCar();
return mycar;
} // this is return by reference(point er)
// less expensive as it only return 4 byte = pointer.

Also for a collection of object like a LinkedList object, since it's
very expensive to return by value, i must use return by
reference(point er):

LinkedList* myfunction(){
LinkedList* list = new LinkedList();
return list;
} // this is return by reference(point er)
// less expensive as it only return 4 byte = pointer.
// instead of return by value to copy all element in the List

>
>I most case, I would perfer to use the static object creation:
MyCar mycar;
since I don't need to worry about delete / free object after creation.

When are the times I must use dynamic creation ( create a pointer )?


One obvious case is when you actually want to create certain things
"dynamically ." Suppose you're writing a game. When the user clicks the
mouse button, you want to make a gun fire a bullet. You don't know at
compile time how many times he might press that button. You would need
to create a new "MyBullet" object every time he presses the button, and
probably "delete" the objects when they hit something, or when they are
far enough away that you can't see them any more. You can't do that in
a clean way without creating the objects dynamically.

A common trick in the old days of C (and even before) was to place a
limit on the number of objects that could be created. That's the
reason, when you play "Galaga," that you can't fire more than two
bullets at a time. If you enforece a limit like this, then you can
declare your objects statically:

MyBullet bullets[2];

And then when the user presses the "fire" button, you have to check and
make sure that at least one of the bullets has already scrolled off the
top of the screen. If it has, you don't actually create anything, you
just move the bullet that's hiding just off the screen back to the tip
of the gun and start it going upward again.

There are certainly benefits to static allocation - speed being a major
one. There's also no possiblity of memory leaks. There are lots of
reasons to use dynamic allocation, but it's never absolutely necessary.
It just makes sense in a lot of cases. It's usually kind of a balancing
act.
In that case, if I used static object allocation, will it crash my
program? Will something like null pointer exception happens? as the
object get destroy automatically after function exit:

void myfunction(){
MyCar mycar = new MyCar();
// mycar is used by other function also after function returns
mycar.AddEventL istener();
// even myfunction returns,
// but mycar still need to listen for events
}
>
Pat
Jun 27 '08 #3
ave
So, if I want to return an object created in a function I better use
dynamic creation?
It depends, on what behaviour you want your application to have and what
type of object you're creating.
// this is more expensive as it copy whole value and return value

<snip>

// less expensive as it only return 4 byte = pointer.
4 bytes != sizeof( pointer ). I mean, it *may* be the size of a pointer. but
it might not, it depends on which compiler you're using and which platform
you're targetting.

The performance difference can vary depending on a many things, not just
whether you pass by value or pointer.
LinkedList* myfunction(){
LinkedList* list = new LinkedList();
return list;
}
// instead of return by value to copy all element in the List
It isn't always about performance, it's not so black and white as that and
your example just seem like you miss the big picture.

In this instance yea, it will be faster. Is there another way that's even
faster? Is this safe? Is there another way that's even safer? which is more
important? can you get both by not doing either? Which other ways can you
achieve this result? Why is this function creating a local list and then
returning it? Is there another way of doing it that's faster? safer?

Just saying "hey, this way is faster right? so I'll do it this way then..."
means you've skipped just about everything that makes programming...
programming!

ave
Jun 27 '08 #4
On Tue, 22 Apr 2008 15:09:06 +0100, "ave" <av*@nomailplea se.com>
wrote:
>So, if I want to return an object created in a function I better use
dynamic creation?

It depends, on what behaviour you want your application to have and what
type of object you're creating.
> // this is more expensive as it copy whole value and return value

<snip>

// less expensive as it only return 4 byte = pointer.

4 bytes != sizeof( pointer ). I mean, it *may* be the size of a pointer. but
it might not, it depends on which compiler you're using and which platform
you're targetting.

The performance difference can vary depending on a many things, not just
whether you pass by value or pointer.
>LinkedList* myfunction(){
LinkedList* list = new LinkedList();
return list;
}
// instead of return by value to copy all element in the List

It isn't always about performance, it's not so black and white as that and
your example just seem like you miss the big picture.

In this instance yea, it will be faster. Is there another way that's even
faster? Is this safe? Is there another way that's even safer? which is more
important? can you get both by not doing either? Which other ways can you
achieve this result? Why is this function creating a local list and then
returning it? Is there another way of doing it that's faster? safer?

Just saying "hey, this way is faster right? so I'll do it this way then..."
means you've skipped just about everything that makes programming...
programming!

ave

then static object creation should be used in global variables (just
like static variable) that there is "ONLY ONE" copy of the object in
the life time of an applicatoin, like follows,

CConfiguration g_Configuration ;

is a global variable, then it only have a 1 copy / object in whole
application.

then that means alot of time, I must use dynamic object creation,
since alot of objects won't be needed, until some condition is meet,
then I create the object at runtime.

since I heard someone said I should use static object create like
MyCar mycar;
whenever I can, but most of the code I seen they just dynamicly create
the object using "new" operator.

=============== ====
#include "Config.h"

//--------------------------------------------------------------
CConfiguration g_Configuration ;

//--------------------------------------------------------------
CConfiguration: :CConfiguration () {
Initialize();
}

//--------------------------------------------------------------
void CConfiguration: :Initialize() {
//m_eControllerTy pe = CONTROLLER_TYPE _REMOTE;
m_eControllerTy pe = CONTROLLER_TYPE _MOUSE;
m_bFullScreen = false;
m_bProjectSplas hScreen = false;
m_szComPort="CO M3";
m_eRemoteType=R EMOTE_TYPE_PEAN UT;

switch (1) {
case 1: {
m_DisplayWidth = 1366;
m_DisplayHeight = 768;
} break;
case 2: {
m_DisplayWidth = 1024;
m_DisplayHeight = 768;
} break;
}
}
=============== ====
Jun 27 '08 #5
On Apr 22, 10:52 am, worlman...@yaho o.com wrote:
For pointer and non-pointer initialization of an object like
MyCar mycar;
MyCar* mycar = new MyCar();
I heard from other people saying if object i create must live
outside scape, then I use pointer version, else if only use
object for a limited scope, then use non-pointer version.
It's more complex than that. In general, if you have an object
with identity and an arbitrary lifetime, you need dynamic
allocation. You also need dynamic allocation if the type or
size aren't known at compile time.

If you don't need dynamic allocation, you shouldn't use it. If
the objects don't have identity, for example, you should prefer
returning a copy of it to returning a pointer to a dynamically
allocated instance.
Does limited scope means the object is only used in the same
function like:
void myfunction(){
MyCar mycar;
// mycar is only used inside this function
}
and if mycar is used by outside scope means:
void myfunction(){
MyCar* mycar = new MyCar();
// mycar is used by other function also after function returns
mycar->AddEventListen er();
// even myfunction returns,
// but mycar still need to listen for events
}
Don't confuse scope with object lifetime. An object with
automatic lifetime does disappear when it last goes out of
scope, but as long as it exists, it can be used even in places
where it isn't in scope, e.g. because you've passed a pointer or
a reference to it.

Scope concerns the name, not the object, and defines where the
name is visible. Dynamic allocation or not concerns lifetime,
when the object is created and when it is destructed.
I most case, I would perfer to use the static object creation:
MyCar mycar;
since I don't need to worry about delete / free object after
creation.
Attention: static lifetime is still another thing. Objects
defined at namespace scope, or with the keyword static, have
static lifetime. Objects defined at local scope without the
keyword static have automatic lifetime. Objects created with a
new expression have dynamic lifetime. Temporaries and
exceptions have special lifetimes of their own.

In general, the compiler will manage both the lifetime and the
memory in all cases but dynamic lifetime. If one of the
compiler managed lifetimes can be used, you definitely should
prefer it.
When are the times I must use dynamic creation ( create a
pointer )?
Typically, when an object has identity (and can't be copied),
and an explicit lifetime. Sometimes, however, because you don't
know the type or the number of objects at compile time (although
dynamic containers like std::vector mean that most of the time,
you don't need dynamic allocation even when you don't know the
number at compile time).

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #6
On Apr 22, 12:52 pm, worlman...@yaho o.com wrote:
On Tue, 22 Apr 2008 09:18:10 GMT, Your Name <n...@none.none wrote:
Does limited scope means the object is only used in the
same function
"Scope" generally means "within the inner-most open/close
braces." For example, in C++ you can even do things like:
void func(int x, int z)
{
if (x == 5)
{
int y = x + 1;
y *= z;
}
y += 14; // (Compile error because "y" is out of scope here!)
}
So, if I want to return an object created in a function I
better use dynamic creation?
No. Why?
MyCar myfunction(){
MyCar mycar;
return mycar;
} // this is return by value
// this is more expensive as it copy whole value and return value
MyCar* myfunction(){
MyCar* mycar = new MyCar();
return mycar;
} // this is return by reference(point er)
// less expensive as it only return 4 byte = pointer.
Maybe. If the program has a performance problem, and the
profiler says it is due to copying return values, you will have
to change to returning a pointer, probably with dynamic
allocation. (In that case, you should consider using something
like boost::shared_p tr.) Most of the tiem, however, it's not
really an issue, and the distinction is more one of whether the
object has identity or not. If it has identity, you can't
return by value. (And a pointer is 8 bytes on most of the
machines I work on.)
Also for a collection of object like a LinkedList object,
since it's very expensive to return by value, i must use
return by reference(point er):
LinkedList* myfunction(){
LinkedList* list = new LinkedList();
return list;
} // this is return by reference(point er)
This is a special case. First, I wouldn't worry about it any
more than the above until it was proven to be a performance
problem. (I once returned a linked list with some 60000
elements by value. Since the function was only called six times
in a program which otherwise took two or three hours to run, it
wasn't a problem.) If it does turn out to be a performance
problem, however, an alternative (and generally better) solution
is to have the caller provide the container, e.g.:

void
myFunction(
LinkedList& result )
{
result.clear() ;
// fill the list...
}

It's less convenient for the caller than return by value, but
still more convenient than having to handle a dynamically
allocated object.

But again, it's an optimization to be considered if, and only
if, you have a real performance problem.
// less expensive as it only return 4 byte = pointer.
// instead of return by value to copy all element in the List
I most case, I would perfer to use the static object creation:
MyCar mycar;
since I don't need to worry about delete / free object after creation.
When are the times I must use dynamic creation ( create a pointer )?
One obvious case is when you actually want to create certain
things "dynamicall y." Suppose you're writing a game. When
the user clicks the mouse button, you want to make a gun fire
a bullet. You don't know at compile time how many times he
might press that button. You would need to create a new
"MyBullet" object every time he presses the button, and
probably "delete" the objects when they hit something, or
when they are far enough away that you can't see them any
more. You can't do that in a clean way without creating the
objects dynamically.
A common trick in the old days of C (and even before) was to
place a limit on the number of objects that could be created.
That's the reason, when you play "Galaga," that you can't
fire more than two bullets at a time. If you enforece a
limit like this, then you can declare your objects
statically:
MyBullet bullets[2];
And then when the user presses the "fire" button, you have to
check and make sure that at least one of the bullets has
already scrolled off the top of the screen. If it has, you
don't actually create anything, you just move the bullet
that's hiding just off the screen back to the tip of the gun
and start it going upward again.
There are certainly benefits to static allocation - speed
being a major one. There's also no possiblity of memory
leaks. There are lots of reasons to use dynamic allocation,
but it's never absolutely necessary. It just makes sense in
a lot of cases. It's usually kind of a balancing act.
In that case, if I used static object allocation, will it crash my
program?
In which case? If you don't know the number of objects up
front, you can't use automatic lifetime, at least not in the
end. Today, of course, you can get the same effect as automatic
lifetime by using things like std::vector---there is dynamic
allocation, but it all takes place under the hood, so to speak,
so you don't have to worry about it.
Will something like null pointer exception happens? as the
object get destroy automatically after function exit:
void myfunction(){
MyCar mycar = new MyCar();
Either this should be a pointer, or you shouldn't use new.
// mycar is used by other function also after function returns
mycar.AddEventL istener();
// even myfunction returns,
// but mycar still need to listen for events
}
Objects with automatic lifetime end their lifetime at the end of
the scope in which they were created. If the object lifetime
must persist after this, and identity is important (and it is if
other objects have pointers to the object), then you must use
dynamic lifetime. Presumably, one of the "events", above, will
cause the object to self destruct, and the constructor will, of
course, ensure that all listeners are correctly informed, and
get rid of their pointers to the object. (In my own code, I'll
occasionally have things like:
new SomeObjectType ;
where I don't save the pointer resulting from the new
expression. The constructor of the object has registered itself
as an event listener somewhere, however, or in a map where it
can be found by looking up some external name, so the object
will be informed, and will delete itself correctly when the time
comes.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #7

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

Similar topics

5
3748
by: klaus triendl | last post by:
hi, recently i discovered a memory leak in our code; after some investigation i could reduce it to the following problem: return objects of functions are handled as temporary objects, hence their dtor is called immediately and not at the end of the function. to be able to use return objects (to avoid copying) i often assign them to a const reference. now, casting a const return object from a function to a non-const reference to this...
3
12255
by: Mario | last post by:
Hello, I couldn't find a solution to the following problem (tried google and dejanews), maybe I'm using the wrong keywords? Is there a way to open a file (a linux fifo pipe actually) in nonblocking mode in c++? I did something ugly like --- c/c++ mixture --- mkfifo( "testpipe", 777);
25
7628
by: Yves Glodt | last post by:
Hello, if I do this: for row in sqlsth: ________pkcolumns.append(row.strip()) ________etc without a prior:
32
4519
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
8
3506
by: Bern McCarty | last post by:
Is it at all possible to leverage mixed-mode assemblies from AppDomains other than the default AppDomain? Is there any means at all of doing this? Mixed-mode is incredibly convenient, but if I cannot load/unload/reload extensions into my large and slow-to-load application during development without restarting the process then the disadvantages may outweigh the advantages. I've got a mixed-mode program in which I create a new AppDomain...
11
3441
by: ypjofficial | last post by:
Hello All, So far I have been reading that in case of a polymorphic class ( having at least one virtual function in it), the virtual function call get resolved at run time and during that the vtable pointer is made use of.. eg. class one {
2
6114
by: Ian825 | last post by:
I need help writing a function for a program that is based upon the various operations of a matrix and I keep getting a "non-aggregate type" error. My guess is that I need to dereference my pointers, but I'm not sure. Please help. The code: void equate(matrix *A, matrix *B) { int i, j; assert(A.row_dim == B.col_dim && A.col_dim == B.col_dim); for(i=0; i < A.row_dim; i++) for(j=0; j < A.col_dim; j++)
0
2343
by: amitvps | last post by:
Secure Socket Layer is very important and useful for any web application but it brings some problems too with itself. Handling navigation between secure and non-secure pages is one of the cumbersome jobs. When a non-secure page references a secure page with relative URL, the web server generates error until absolute URL with https prefix is used. On the other hand when a secure page references a non-secure page, the non-secure page will be...
399
12849
by: =?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= | last post by:
PEP 1 specifies that PEP authors need to collect feedback from the community. As the author of PEP 3131, I'd like to encourage comments to the PEP included below, either here (comp.lang.python), or to python-3000@python.org In summary, this PEP proposes to allow non-ASCII letters as identifiers in Python. If the PEP is accepted, the following identifiers would also become valid as class, function, or variable names: Löffelstiel,...
12
29899
by: puzzlecracker | last post by:
is it even possible or/and there is a better alternative to accept input in a nonblocking manner?
0
8837
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8728
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9130
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9059
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8005
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4484
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3187
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2572
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2129
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.