473,327 Members | 1,920 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,327 software developers and data experts.

reference and pointer and function argument copy

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....36bcd62faa954a

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

Aug 6 '06 #1
8 1734
* jo************@gmail.com:
>
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....36bcd62faa954a

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).

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Aug 6 '06 #2
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.
Yesss, sure !! sorry for the stupid question... i was just thinking
about return type :-(

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

Aug 6 '06 #3
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.

--

Frederick Gotham
Aug 7 '06 #4
Frederick Gotham <fg*******@SPAM.comwrites:
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 = ...
Out of curiosity, what has making it a const got to do with deleting it later?
Aug 7 '06 #5
Richard posted:
>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?

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.

--

Frederick Gotham
Aug 7 '06 #6
Frederick Gotham wrote:
[...]
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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 7 '06 #7
Frederick Gotham <fg*******@SPAM.comwrites:
Richard posted:
>>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?


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.

Aug 7 '06 #8
Victor Bazarov posted:
Frederick Gotham wrote:
>[...]
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];
}

--

Frederick Gotham
Aug 7 '06 #9

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

Similar topics

36
by: Riccardo Rossi | last post by:
Hi all! How does Python pass arguments to a function? By value or by reference? Thanks, Riccardo Rossi.
14
by: dumboo | last post by:
hi there i m little bit confused over the following problem, i have understood wt the following code is doing...but not able to get the actual techinical stuff.....i have had a lot of hot debate...
3
by: jimjim | last post by:
Hello, My question concerns as to how a pointer is passed by reference as a function argument. The following is from code taken from the MICO implementation of the CORBA specification. in...
9
by: Sandy | last post by:
Hi, In one of my interview I was asked a question, whether using pointers for argument is efficient then reference or not. i.e. void fun(Complex *p) void fun(Complex &ref) can somebody...
7
by: Marcelo | last post by:
Hi everybody, I don't understand why I am having a problem in this code. The problem is that my pointer *phist in main method, it is declared. Then I send the pointer to my method, and this...
14
by: key9 | last post by:
Hi All On coding , I think I need some basic help about how to write member function . I've readed the FAQ, but I am still confuse about it when coding(reference / pointer /instance) , so I...
8
by: toton | last post by:
HI, One more small doubt from today's mail. I have certain function which returns a pointer (sometimes a const pointer from a const member function). And certain member function needs reference...
10
by: Robert Dailey | last post by:
Hi, I noticed in Python all function parameters seem to be passed by reference. This means that when I modify the value of a variable of a function, the value of the variable externally from the...
14
by: Siegfried Heintze | last post by:
Why does VB.NET V2 force me to pass by value for my set function? When I try to change it to const byref it gives me a syntax error. It seems very inefficient to be passing strings around by value...
275
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.