472,985 Members | 2,328 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,985 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 1717
* 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
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.