reference and pointer and function argument copy

J

joel.winteregg

Hi all,


I "learnt" C++ a few years ago and then i have been using C for a
couple of month and i'm now trying to get back to the ++ world (but
with some troubles...). I have some problem to understand why a "new"
return a pointer and not a reference. Here are explanations:


/* to get my object in heap */
MyClass* objectPtr = new MyClass();

If i want to handle my object using a reference i will have to do
something like this:

MyClass& objectRef = *objectPtr;
/* or all in one */
MyClass& objectRef = *(new MyClass());

Why the use of "new" wasn't done to get reference and malloc to get
pointers ? wouldn't it be easier ?

I also have an other question about function call using references.
During my search i have been reading this post:
http://groups.google.com/group/comp...a954a?lnk=st&q=&rnum=7&hl=en#0436bcd62faa954a

which confuse me a lot. Is it right that a function which return an
object ref will return it using the copy constructor (a copy of it ) ?

MyClass& GetMyClass() { return myObject; }
MyClass& myObj = GetMyClass();

I thought that the "return MyClass" statement would return the ref of
"myObject" and not a copy of it !! (Hope the object was allocated using
new and not statically ;-) )

I would do it by copy, like this:

MyClass GetMyClass() { return myObject; }
/* object statically allocated */
MyClass myObj = GetMyClass();

Thanks a lot for your help !!

Joël
 
A

Alf P. Steinbach

* (e-mail address removed):
I "learnt" C++ a few years ago and then i have been using C for a
couple of month and i'm now trying to get back to the ++ world (but
with some troubles...). I have some problem to understand why a "new"
return a pointer and not a reference.

Mostly it's a convention, that dynamically allocated objects are
referred to via pointers, not references. But there's also a historical
part (pre-standard compilers could let new return a nullpointer instead
of throwing an exception) and a consistency issue (new(nothrow) does
return a nullpointer instead of throwing an exception). Ideally, in a
language designed from scratch, new should perhaps return a reference.

Here are explanations:

/* to get my object in heap */
MyClass* objectPtr = new MyClass();

If i want to handle my object using a reference i will have to do
something like this:

MyClass& objectRef = *objectPtr;
/* or all in one */
MyClass& objectRef = *(new MyClass());

Why the use of "new" wasn't done to get reference and malloc to get
pointers ? wouldn't it be easier ?

'new' and 'malloc' do very different things. The main difference isn't
the result type, but that 'new' is the C++ device for calling a
constructor on some storage, transforming that storage into a valid
object. The ordinary 'new' guarantees that on successful execution you
have an initialized object at hand, and otherwise (an exception occurs)
that the allocated memory is freed; 'malloc' just allocates memory.

I also have an other question about function call using references.
During my search i have been reading this post:
http://groups.google.com/group/comp...a954a?lnk=st&q=&rnum=7&hl=en#0436bcd62faa954a

which confuse me a lot. Is it right that a function which return an
object ref will return it using the copy constructor (a copy of it ) ?

No. It just returns a reference to whatever you specify. Which should
be an object that doesn't cease to exist when the function returns.

MyClass& GetMyClass() { return myObject; }
MyClass& myObj = GetMyClass();

I thought that the "return MyClass" statement would return the ref of
"myObject" and not a copy of it !!

It does.

(Hope the object was allocated using
new and not statically ;-) )

It doesn't matter how the object was allocated, except if that means the
object won't exist after the function return (in which case you have a
dangling reference, not a good idea).
 
J

joel.winteregg

'new' and 'malloc' do very different things. The main difference isn't
the result type, but that 'new' is the C++ device for calling a
constructor on some storage, transforming that storage into a valid
object. The ordinary 'new' guarantees that on successful execution you
have an initialized object at hand, and otherwise (an exception occurs)
that the allocated memory is freed; 'malloc' just allocates memory.

Yesss, sure !! sorry for the stupid question... i was just thinking
about return type :-(

No. It just returns a reference to whatever you specify. Which should
be an object that doesn't cease to exist when the function returns.

Oufffff !! i will sleep well now !! (i just did a test using a simple
class after my post to rest my mind...)
It doesn't matter how the object was allocated, except if that means the
object won't exist after the function return (in which case you have a
dangling reference, not a good idea).

Took me a few seconds to understand what you mean ! but i think i get
it... for me the statically allocated == on stack which mean it is
automaticaly cleaned after the function call -> problem if you return
the ref of it. And dynamical == on heap -> OK for ever. But i think
that your sentence say that even if it's done on heap you can have
problems if you do a delete of the object before the function return it
;-). Is it your sentence translation ?

Thanks a lot for you help !

Jo
 
F

Frederick Gotham

Joel posted:
Hi all,


I "learnt" C++ a few years ago and then i have been using C for a
couple of month and i'm now trying to get back to the ++ world (but
with some troubles...). I have some problem to understand why a "new"
return a pointer and not a reference.


There's nothing to understand -- it just does.

Here are explanations:


/* to get my object in heap */
MyClass* objectPtr = new MyClass();


You'll probably want to make that const if you intend on deleting it later:


MyClass *const p = ...

If i want to handle my object using a reference i will have to do
something like this:

MyClass& objectRef = *objectPtr;
/* or all in one */
MyClass& objectRef = *(new MyClass());


MyClass &r = *new MyClass;

Why the use of "new" wasn't done to get reference and malloc to get
pointers ? wouldn't it be easier ?


Not when it comes to arrays.
 
R

Richard

Frederick Gotham said:
Joel posted:



There's nothing to understand -- it just does.




You'll probably want to make that const if you intend on deleting it later:


MyClass *const p = ...

Out of curiosity, what has making it a const got to do with deleting it later?
 
F

Frederick Gotham

Richard posted:
Out of curiosity, what has making it a const got to do with deleting it
later?


You must supply "delete" with the same address returned from "new". By
defining the variable as const, you make sure that the address won't
change.

The following compiles no problem:

int *p = new int[5];

++p;

delete [] p;

However, the following fails to compile:

int *const p = new int[5];

++p; /* Const violation */

delete [] p;

I bring this concept further to define functions whose return value is
const:

int *const Func()
{
return new int[5];
}

It doesn't really buy you anything, but it's intuitive.
 
V

Victor Bazarov

Frederick said:
[...]
I bring this concept further to define functions whose return value is
const:

int *const Func()
{
return new int[5];
}

It doesn't really buy you anything, but it's intuitive.

How is it intuitive? I would consider using it _only_ if the following
failed to compile.

int * p = Func();
++p;
delete[] p;

V
 
R

Richard

Frederick Gotham said:
Richard posted:



You must supply "delete" with the same address returned from "new". By
defining the variable as const, you make sure that the address won't
change.

Aha, so it doesnt actually have anything to do with the delete. You just
want to make sure the pointer doesnt change. No worries.
 
F

Frederick Gotham

Victor Bazarov posted:
Frederick said:
[...]
I bring this concept further to define functions whose return value is
const:

int *const Func()
{
return new int[5];
}

It doesn't really buy you anything, but it's intuitive.

How is it intuitive? I would consider using it _only_ if the following
failed to compile.

int * p = Func();
++p;
delete[] p;

V


It's just another way of writing:

int *Func() /* Remember to keep track of the address */
{
return new int[5];
}
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top