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

Return pointers or references?

Hi,

I'm designing an interface for a shared library, and I would like to
know if there is a standard about how to return an object to the user. I
will use exceptions to report errors, so there are at least four ways to
do it.

For example if we have a method named M, that receives a reference to
parameter p and returns object o.

1 - virtual o& M(p& parameter) throw(Exception1, Exception2...

2 - virtual o* M(p& parameter) throw(Exception1, Exception2...

3 - virtual void M(p& parameter, o& returnVal) throw(Exception1,
Exception2...

4 - virtual void M(p& parameter, o* returnVal) throw(Exception1,
Exception2...
Probably there is no convention about it and is only a mater of taste,
but I would like to know some opinions.

Best regards,
Gama Franco

Jul 22 '05 #1
14 1986
Gama Franco wrote:
I'm designing an interface for a shared library, and I would like to
know if there is a standard about how to return an object to the user. I
will use exceptions to report errors, so there are at least four ways to
do it.

For example if we have a method named M, that receives a reference to
parameter p and returns object o.

1 - virtual o& M(p& parameter) throw(Exception1, Exception2...

2 - virtual o* M(p& parameter) throw(Exception1, Exception2...

3 - virtual void M(p& parameter, o& returnVal) throw(Exception1,
Exception2...

4 - virtual void M(p& parameter, o* returnVal) throw(Exception1,
Exception2...
Probably there is no convention about it and is only a mater of taste,
but I would like to know some opinions.


Smart pointers?

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces
Jul 22 '05 #2
Gama Franco wrote:
I'm designing an interface for a shared library, and I would like to
know if there is a standard about how to return an object to the user. I
will use exceptions to report errors, so there are at least four ways to
do it.
More, actually. You still can return by value. And often that is
the preferred method. You can pass a pointer to an object by reference
and you can pass a pointer to an object by pointer.
For example if we have a method named M, that receives a reference to
parameter p and returns object o.
If it "returns object o", why are you trying to return a pointer or
a reference? Doesn't "returns object" mean "by value"?

1 - virtual o& M(p& parameter) throw(Exception1, Exception2...

2 - virtual o* M(p& parameter) throw(Exception1, Exception2...

3 - virtual void M(p& parameter, o& returnVal) throw(Exception1,
Exception2...

4 - virtual void M(p& parameter, o* returnVal) throw(Exception1,
Exception2...
Probably there is no convention about it and is only a mater of taste,
but I would like to know some opinions.


The differences are significant. First of all, you clearly returning
a pointer or a reference to a _non_const_ object. Where is that object
residing? Is it part of the object for which the member function 'M'
is called? Then returning a reference or a pointer is often OK, but
the lifetime of the "returned" object will depend on the lifetime of
the object for which you call 'M'. So, there is a dependency, which
many prefer to avoid.

Second, a pointer can be null, so any time somebody returns a pointer
to me, I need to write code to verify that it's valid. A reference can
never be null, no matter what some of your college buddies say. So,
here is one important difference. Another difference is that it's much
easier to deal with pointers if they are to a dynamically created object.
No, it's not impossible to work with a reference in that case

int &ir = *(new int(42));
delete &ir;

but it's ugly. So, if you're creating an object in free store, return
a pointer. Also, thoroughly document that fact so that the user won't
forget to dispose of the object properly (in the case of returning by
value there is no disposal headache).

Cases 3 and 4 assume that (a) the object exists outside and (b) its type
provides some kind of assignment semantics. In that case, you have more
of a question "what's the preferred way of passing objects into functions"
and not "what's the preferred way of returning objects". So, it's quite
different from the first two.

You could merge the cases 3 and 4 into "pass a pointer to an object by
reference" so that you could change it inside the function to point to
something meaningful. In that case the user doesn't have to create
an object before calling your function and you can return the address of
something allocated dynamically. You cannot have a reference to another
reference, so there is only one more case you didn't mention: pass
a pointer to a pointer:

virtual void M(p& parameter, o** returnValPtr) throw(Exception1, ..

which is not bad, but the same implication applies: _you_ need to check
that I didn't pass a null pointer to you, and when the function returns,
I have to check that the value of 'returnValPtr' is not null before I
can use the object.

Victor
Jul 22 '05 #3
Gama Franco wrote:

I'm designing an interface for a shared library,
and I would like to know
if there is a standard about how to return an object to the user. I
will use exceptions to report errors,
so there are at least four ways to do it.

For example if we have a method named M,
that receives a reference to parameter p and returns object o.

1 - virtual o& M(p& parameter) throw(Exception1, Exception2...

2 - virtual o* M(p& parameter) throw(Exception1, Exception2...

3 - virtual void M(p& parameter, o& returnVal) throw(Exception1,
Exception2...

4 - virtual void M(p& parameter, o* returnVal) throw(Exception1,
Exception2...
Probably there is no convention about it and is only a matter of taste,
but I would like to know some opinions.


None of the above.
Use

virtual o M(const p& parameter) const;

instead. Pass by *const* reference and return by value.
Jul 22 '05 #4
E. Robert Tisdale wrote:
Gama Franco wrote:

I'm designing an interface for a shared library, and I would like to
know if there is a standard about how to return an object to the user.
I will use exceptions to report errors, so there are at least four
ways to do it.

For example if we have a method named M, that receives a reference to
parameter p and returns object o.

1 - virtual o& M(p& parameter) throw(Exception1, Exception2...

2 - virtual o* M(p& parameter) throw(Exception1, Exception2...

3 - virtual void M(p& parameter, o& returnVal) throw(Exception1,
Exception2...

4 - virtual void M(p& parameter, o* returnVal) throw(Exception1,
Exception2...
Probably there is no convention about it and is only a matter of
taste, but I would like to know some opinions.

None of the above.
Use

virtual o M(const p& parameter) const;

instead. Pass by *const* reference and return by value.

Hi,

I forgot to mention something very important. One of the requisites is
efficiency. I mean, the API should run as fast as possible (it deals
with scientific data aquisition).

That is the reason why I only placed the return value as a reference or
a pointer.

Thanks in advance,
Gama Franco

Jul 22 '05 #5
"Gama Franco" <ga*********@clix.pt> wrote...
[..]
I forgot to mention something very important. One of the requisites is
efficiency. I mean, the API should run as fast as possible (it deals
with scientific data aquisition).

That is the reason why I only placed the return value as a reference or
a pointer.


You didn't mention how you'd be using the returned value or how you'd
be calling your functions.

V
Jul 22 '05 #6
> >> I'm designing an interface for a shared library, and I would like to
know if there is a standard about how to return an object to the user.
I will use exceptions to report errors, so there are at least four
ways to do it.

For example if we have a method named M, that receives a reference to
parameter p and returns object o.

1 - virtual o& M(p& parameter) throw(Exception1, Exception2...

2 - virtual o* M(p& parameter) throw(Exception1, Exception2...

3 - virtual void M(p& parameter, o& returnVal) throw(Exception1,
Exception2...

4 - virtual void M(p& parameter, o* returnVal) throw(Exception1,
Exception2...
Probably there is no convention about it and is only a matter of
taste, but I would like to know some opinions.

None of the above.
Use

virtual o M(const p& parameter) const;

instead. Pass by *const* reference and return by value.

Hi,

I forgot to mention something very important. One of the requisites is
efficiency. I mean, the API should run as fast as possible (it deals
with scientific data aquisition).


As mentioned virtual o M(...) is the most elegant solution. Often the
implemention is that the caller allocates the memory for o and M initializes
it with its return statement, which often defaults to a simple copy
operation. If you want to get rid of the construction, copying and
desctruction of the object for each call, you hae to use method 3 or 4. They
are equal in terms of efficiency. Whether you use pointer or reference does
not matter in terms of effiency. I prefer using references to emphasize,
that it is not an array.
Your methods 1 and 2 have the usual problems related to allocation and
deallocation:
- An often made mistake is to return a local object, which goes out of scope
when the function terminates.
- It is not clear who is the owner of the objects returned. If they are
owned by a vector, then the caller should not clean them up. Otherwise it
might be the task of the caller to clean them up. Or there might be some
deallocation function in the library...
Usually I use method 1 and 2 only when the objects are owned by some list or
vector, where method 3 and 4 are less efficient.

Niels Dybdahl
Jul 22 '05 #7
>> 3 - virtual void M(p& parameter, o& returnVal) throw(Exception1,
Exception2...


Is it fair to say that, following your reasoning, this is generally the
best option of the four? Maybe it's more a matter of personal coding
style than of following accepted standards, but :

1.The returnVal is completely 'managed' by the client. So :
- There's no danger of a member function lifting an object outside
it's scope (as in option 1).
- There's no need documenting that the allocated object should be freed
by the client (as in option 2).
2.returnVal doesn't have to be checked for the null value
(as in option 2 + 4).
3.Use of pointers is avoided, which is always good for readability.

Bart

Jul 22 '05 #8
Bart Blommerde wrote:
3 - virtual void M(p& parameter, o& returnVal) throw(Exception1,
Exception2...

Is it fair to say that, following your reasoning, this is generally the
best option of the four? Maybe it's more a matter of personal coding
style than of following accepted standards, but :

1.The returnVal is completely 'managed' by the client. So :
- There's no danger of a member function lifting an object outside
it's scope (as in option 1).
- There's no need documenting that the allocated object should be freed
by the client (as in option 2).
2.returnVal doesn't have to be checked for the null value
(as in option 2 + 4).
3.Use of pointers is avoided, which is always good for readability.


Out of four presented, yes, probably. Out of all available, questionable.
I'd still return by value and let the compiler optimise the hell out of
it all. It's just semantically clearer. When you write

SomeClass someObject(blah); // define+initialise
...
someOtherObject.M(someParameter, someObject);

(which is what you're expected to do in the case 3) it is unclear for the
reader what's happening. For all we know, M is a void member (that's true
according to the case 3 declaration) that takes 2 arguments (that's also
true) and does something to the object 'someOtherObject', and not to its
second argument.

V
Jul 22 '05 #9
In article <41**************@clix.pt>,
Gama Franco <ga*********@clix.pt> wrote:
E. Robert Tisdale wrote:
Gama Franco wrote:

I'm designing an interface for a shared library, and I would like to
know if there is a standard about how to return an object to the user.
I will use exceptions to report errors, so there are at least four
ways to do it.

For example if we have a method named M, that receives a reference to
parameter p and returns object o.

1 - virtual o& M(p& parameter) throw(Exception1, Exception2...

2 - virtual o* M(p& parameter) throw(Exception1, Exception2...

3 - virtual void M(p& parameter, o& returnVal) throw(Exception1,
Exception2...

4 - virtual void M(p& parameter, o* returnVal) throw(Exception1,
Exception2...
Probably there is no convention about it and is only a matter of
taste, but I would like to know some opinions.

None of the above.
Use

virtual o M(const p& parameter) const;

instead. Pass by *const* reference and return by value.

Hi,

I forgot to mention something very important. One of the requisites is
efficiency. I mean, the API should run as fast as possible (it deals
with scientific data aquisition).

That is the reason why I only placed the return value as a reference or
a pointer.


Yet you are making the function virtual? Try returning the object by
const value first, if profiling shows this is actually a problem (highly
unlikely IMO) then change it to const reference. No other code will need
to change in this case.
Jul 22 '05 #10
Daniel T. wrote:
[...] Try returning the object by
const value first, [...]


Top-level const qualifiers are meaningless in most situations. And
I mean

const int foo();
void foo(const int);

V
Jul 22 '05 #11
Niels Dybdahl wrote:
Use

virtual o M(const p& parameter) const;

instead. Pass by *const* reference and return by value.
I forgot to mention something very important.
One of the requisites is efficiency.
I mean, the API should run as fast as possible
(it deals with scientific data aquisition).
As mentioned virtual o M(...) is the most elegant solution.
Often the implemention is that the caller allocates the memory for o
and M initializes it with its return statement,
which often defaults to a simple copy operation.


No.
A good optimizing C++ compiler should implement
the Named Return Value Optimization (NRVO).
When a function returns the value of a local variable
the optimizing compiler interprets the local variable
as a reference to the return value and initializes it directly --
*no* copy is required!
Return by value costs no more than any of the other options
that Gama Franco listed.

If your compiler does not implement the NRVO,
you must not be concerned about efficiency or performance
or you should be shopping for a better optimizing C++ compiler.
If you want to get rid of the construction, copying and
destruction of the object for each call,
you [must] use method 3 or 4. They are equal in terms of efficiency.
Whether you use pointer or reference does not matter in terms of effiency.
I prefer using references to emphasize, that it is not an array.


This probably isn't a good idea.

In-place operations (functions that modify objects)
should be of the form:

o& o::M(const p& parameter);

and return a reference to the object.
Jul 22 '05 #12
E. Robert Tisdale wrote:
Niels Dybdahl wrote:
Use

virtual o M(const p& parameter) const;

instead. Pass by *const* reference and return by value.
I forgot to mention something very important. One of the requisites
is efficiency. I mean, the API should run as fast as possible (it
deals with scientific data aquisition).

As mentioned virtual o M(...) is the most elegant solution. Often the
implemention is that the caller allocates the memory for o and M
initializes it with its return statement, which often defaults to a
simple copy operation.

No.
A good optimizing C++ compiler should implement
the Named Return Value Optimization (NRVO).
When a function returns the value of a local variable
the optimizing compiler interprets the local variable
as a reference to the return value and initializes it directly --
*no* copy is required!
Return by value costs no more than any of the other options
that Gama Franco listed.

If your compiler does not implement the NRVO,
you must not be concerned about efficiency or performance
or you should be shopping for a better optimizing C++ compiler.
If you want to get rid of the construction, copying and
destruction of the object for each call, you [must] use method 3 or
4. They are equal in terms of efficiency. Whether you use pointer or
reference does not matter in terms of effiency. I prefer using
references to emphasize, that it is not an array.

This probably isn't a good idea.

In-place operations (functions that modify objects)
should be of the form:

o& o::M(const p& parameter);

and return a reference to the object.

Hi,

I do I know if my compiler does that kind of optimization?
The code will compile in a great number of versions of g++, and probably
also in the default compiler of Solaris.
The program will be used for data aquisition, dealing with data in the
order of hundreds of megabytes per second. Since we are dealing with the
refractoring of an existing API, I really would like to make a
consistent choice without affecting the efficiency of the existing code.
If most of the compilers use that kind of optimization, probably return
by value may be the best choice, since the object will get destroyed
when the variable gets out of scope.

Best regards,
Gama Franco

Jul 22 '05 #13
Gama Franco wrote:
I do I know if my compiler does that kind of optimization?
The code will compile in a great number of versions of g++,
My compiler:
g++ --version g++ (GCC) 3.3.3 20040412 (Red Hat Linux 3.3.3-7)

does it.
and probably also in the default compiler of Solaris.
Later versions of the Solaris C++ compiler do it too.
The program will be used for data aquisition, dealing with data in the
order of hundreds of megabytes per second. Since we are dealing with the
refractoring of an existing API, I really would like to make a
consistent choice without affecting the efficiency of the existing code.
If most of the compilers use that kind of optimization,
probably return by value may be the best choice,
It *is* the best choice.
Most modern C++ compilers support the NRVO
but what matters is that there is at least one
good optimizing C++ compiler for each target platform.
You can do your development with whatever compiler is most convenient
and then recompile with your best optimizing C++ compiler
just before you distribute the production release.
since the object will get destroyed when the variable gets out of scope.

Jul 22 '05 #14
Victor Bazarov <v.********@comAcast.net> wrote:
Daniel T. wrote:
[...] Try returning the object by
const value first, [...]


Top-level const qualifiers are meaningless in most situations. And
I mean

const int foo();


When it comes to basic types like 'int' I agree, but not with user
defined types. For example if we have:

value foo();

Then clients can do:

value myValue = foo().modify();

Then changing to 'const value&' will break the program. Better is to
return 'const value' so that clients can't modify the temporary (making
user defined types more like basic types) thus allowing us to change to
a 'const value&' without having to modify any client code.
Jul 22 '05 #15

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

Similar topics

15
by: Web Developer | last post by:
Hi, Can someone provide a short and concise statement(s) on the difference between pointers and references. A graphical representation (via links?) of both would be much appreciated as well. ...
4
by: cppaddict | last post by:
I understand that there are a couple differences between reference variables and pointer: 1) reference variables *must* be initialized. 2) You cannot change what a reference variable refers...
5
by: Neal Coombes | last post by:
Posted to comp.lang.c++.moderated with little response. Hoping for better from the unmoderated groups: -------- Original Message -------- Subject: Return appropriately by value, (smart)...
458
by: wellstone9912 | last post by:
Java programmers seem to always be whining about how confusing and overly complex C++ appears to them. I would like to introduce an explanation for this. Is it possible that Java programmers...
64
by: Zytan | last post by:
I know there are no pointers in C#, but if you do: a = b; and a and b are both arrays, they now both point to the same memory (changing one changes the other). So, it makes them seem like...
13
by: cppquester | last post by:
A colleague told me that there is a rule about good stype that a function in C++ should have only one point of return (ie. return statement). Otherwise there might be trouble. I never heard about...
19
by: MQ | last post by:
Can someone tell me where I should use pointers and where I should use references? In his book, Stroustrup says that you should use pointers for passing arguments that are to be modified, not...
2
by: Sebastian Schucht | last post by:
Hi, I have a templateclass with virtual member-functions, so i can't create instances ... but for returning the result i would like use one. So i replaced the A<TTypefrom the baseclass with the...
68
by: Jim Langston | last post by:
I remember there was a thread a while back that was talking about using the return value of a function as a reference where I had thought the reference would become invalidated because it was a...
29
by: Simon Saize | last post by:
Hi - What's the point of having references (&)? Why don't we just use pointers (*)? Thanks.
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...

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.