473,796 Members | 2,708 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(Exception 1, Exception2...

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

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

4 - virtual void M(p& parameter, o* returnVal) throw(Exception 1,
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 2047
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(Exception 1, Exception2...

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

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

4 - virtual void M(p& parameter, o* returnVal) throw(Exception 1,
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(Exception 1, Exception2...

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

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

4 - virtual void M(p& parameter, o* returnVal) throw(Exception 1,
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(Exception 1, ..

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(Exception 1, Exception2...

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

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

4 - virtual void M(p& parameter, o* returnVal) throw(Exception 1,
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(Exception 1, Exception2...

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

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

4 - virtual void M(p& parameter, o* returnVal) throw(Exception 1,
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*********@cl ix.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(Exception 1, Exception2...

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

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

4 - virtual void M(p& parameter, o* returnVal) throw(Exception 1,
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(Exception 1,
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(Exception 1,
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+initiali se
...
someOtherObject .M(someParamete r, 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 'someOtherObjec t', and not to its
second argument.

V
Jul 22 '05 #9
In article <41************ **@clix.pt>,
Gama Franco <ga*********@cl ix.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(Exception 1, Exception2...

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

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

4 - virtual void M(p& parameter, o* returnVal) throw(Exception 1,
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

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

Similar topics

15
14040
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. WD
4
4959
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 to. My question is: In what situations is it better to use a reference variable over a pointer? Also, are there other differences besides the ones I listed above?
5
3048
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) pointer, or reference Date: 27 Aug 2005 15:13:23 -0400 From: Neal Coombes <nealc@trdlnk.com> Organization: Aioe.org NNTP Server To: (Usenet) Newsgroups: comp.lang.c++.moderated
458
21517
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 simply aren't smart enough to understand C++? This is not merely a whimsical hypothesis. Given my experience with Java programmers --- the code they write and the conversations they have --- Occam's Razor points to this explanation. For example,...
64
3440
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 pointers. Can someone please explain why? thanks. Zytan
13
2916
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 it and doubt it. Anybody heard of it? What would be the advantage? Regards, Marc Example:
19
1993
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 references. Yet, in an interview, he laments the overuse of pointers and such in code. It seems contradictory to me. Why should we not use references instead of pointers? Can someone give me an idea of best practices in this respect? regards,...
2
10330
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 Type from the spezialized class. After this, the error invalid covariant return type occoured. the following minimal sample shows the problem: #include <iostream>
68
4660
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 temporary but it was stated that it would not. This has come up in an irc channel but I can not find the original thread, nor can I get any code to work. Foo& Bar( int Val ) { return Foo( Val ); }
29
1518
by: Simon Saize | last post by:
Hi - What's the point of having references (&)? Why don't we just use pointers (*)? Thanks.
0
9533
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,...
0
10461
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10239
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10190
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
10019
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
9057
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
6796
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4122
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
3
2928
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.