473,881 Members | 1,653 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Function returning a "null" reference object

Hello:

i have a function that reads a file as an argument and returns a reference
to an object that contains some information obtained from the file: FData
&ReadFile(strin g FilePath);

But , for example, when the file doesnt exists, i should not return any
reference to a bad constructed object, so i need something as a NULL
reference object. I suppose i could return a pointer instead, but i have
some code written with references which I´d like to preserve...
¿How can i do that?

Jul 19 '05 #1
7 20390
Pablo J Royo wrote:
Hello:

i have a function that reads a file as an argument and returns a
reference to an object that contains some information obtained from
the file: FData &ReadFile(strin g FilePath);

But , for example, when the file doesnt exists, i should not return
any reference to a bad constructed object, so i need something as a
NULL reference object. I suppose i could return a pointer instead,
but i have some code written with references which I´d like to
preserve...
You can throw an exception.

BTW how do you return that reference? What does it refer to? I hope not an
automatic variable.
¿How can i do that?


No need for that upside down question mark. :-)

--
Attila aka WW
Jul 19 '05 #2
Thanks for your response.
I had an object allocated with new inside the function (FData *pData =
new...) , and i returned its contents (return *pData) but this gave me all
kind of problems when i put the returned object in a STL vector container,
so in fact I changed my declaration to be

FData &ParseFileTags( FData &Ret,char *path)

If all goes well, Ret contains good data after this call and i return that
same object. If not, I dont want to return a reference to that object, but
to another "NULL" object instead, or something that allows me to write

result = ParseFileTags(R et,path);
if (result == NULL)
....
else
.....

I would prefer not to use exceptions, but as i write this i realize it may
be the only true solution...
"Attila Feher" <at**********@l mf.ericsson.se> escribió en el mensaje
news:bk******** **@newstree.wis e.edt.ericsson. se...
Pablo J Royo wrote:
Hello:

i have a function that reads a file as an argument and returns a
reference to an object that contains some information obtained from
the file: FData &ReadFile(strin g FilePath);

But , for example, when the file doesnt exists, i should not return
any reference to a bad constructed object, so i need something as a
NULL reference object. I suppose i could return a pointer instead,
but i have some code written with references which I´d like to
preserve...
You can throw an exception.

BTW how do you return that reference? What does it refer to? I hope not

an automatic variable.
¿How can i do that?


No need for that upside down question mark. :-)

--
Attila aka WW

Jul 19 '05 #3
"Pablo J Royo" <ro***@tb-solutions.com> writes:
Hello:

i have a function that reads a file as an argument and returns a reference
to an object that contains some information obtained from the file: FData
&ReadFile(strin g FilePath);
Make that FData& ReadFile(const string& FilePath).
I'm curious - why are you returning by reference? Is this some static data
in ReadFile()?
But , for example, when the file doesnt exists, i should not return any
reference to a bad constructed object, so i need something as a NULL
reference object. I suppose i could return a pointer instead, but i have
some code written with references which I´d like to preserve...
¿How can i do that?


Depending on whether you can change the signature of ReadFile() and/or
what you want to do in case of error, you have (at least) the following
possibilities:

- add a flag to ReadFile() that indicates whether the read was successfull
i.e. FData& ReadFile (const string& FilePath, bool& Success)
or even bool ReadFile(const string& FilePath, FData& Data)
- throw an exception in case of failure, and handle it in the caller
- implement the NullObject Pattern (see "Refactorin g", Fowler et al); in
short, derive a class NullFData from FData, implement the necessary
member functions as doing nothing or returning default values, and
return a NullFData from ReadFile() if the file doesn't exist

HTH & kind regards
frank

--
Frank Schmitt
4SC AG phone: +49 89 700763-0
e-mail: frankNO DOT SPAMschmitt AT 4sc DOT com
Jul 19 '05 #4
Pablo J Royo wrote:

PLEASE do not top post and SNIP!

http://www.parashift.com/c++-faq-lit...t.html#faq-5.4

Thanx.
Thanks for your response.
I had an object allocated with new inside the function (FData *pData =
new...) , and i returned its contents (return *pData) but this gave
me all kind of problems when i put the returned object in a STL
vector container, so in fact I changed my declaration to be

FData &ParseFileTags( FData &Ret,char *path)
That is a memory leak waiting to happen. Instead of a reference return a
smart pointer. Something like the boost one.

What you do is you are making trial and error to hide your missing knowledge
about new/delete and containers. Not a good think. Have you ever tried to
find out what were those "weird things" with the vector and most importantly
*why*? What you have made here is a program, which will eat up its
resources.
If all goes well, Ret contains good data after this call and i return
that same object. If not, I dont want to return a reference to that
object, but to another "NULL" object instead, or something that
allows me to write

result = ParseFileTags(R et,path);
if (result == NULL)
...
else
....

I would prefer not to use exceptions, but as i write this i realize
it may be the only true solution...

[SNIP]

Not necessarily. You can return a boost::shared_p tr or something like that
and check if it has a valid pointer inside. IIRC it goes exactly like with
a normal pointer.

--
Attila aka WW
Jul 19 '05 #5
"Pablo J Royo" <ro***@tb-solutions.com> wrote in message news:<Hq******* **********@news-reader.eresmas. com>...

<please don't top post - thank you - rearranged>
"Attila Feher" <at**********@l mf.ericsson.se> escribió en el mensaje
news:bk******** **@newstree.wis e.edt.ericsson. se...
Pablo J Royo wrote:
Hello:

i have a function that reads a file as an argument and returns a
reference to an object that contains some information obtained from
the file: FData &ReadFile(strin g FilePath);

But , for example, when the file doesnt exists, i should not return
any reference to a bad constructed object, so i need something as a
NULL reference object. I suppose i could return a pointer instead,
but i have some code written with references which I´d like to
preserve...
You can throw an exception.


<snip>
FData &ParseFileTags( FData &Ret,char *path)

If all goes well, Ret contains good data after this call and i return that
same object. If not, I dont want to return a reference to that object, but
to another "NULL" object instead, or something that allows me to write

result = ParseFileTags(R et,path);
if (result == NULL)
...
else
....

I would prefer not to use exceptions, but as i write this i realize it may
be the only true solution...


You can't have a null reference. That's one of the reasons for
choosing references over pointers in some circumstances. If you want
to return a reference, you'll need to decide what object 'result' will
refer to after the function call if ParseFileTags fails.

GJD
Jul 19 '05 #6
In article <PU************ *****@news-reader.eresmas. com>, royop@tb-
solutions.com says...
Hello:

i have a function that reads a file as an argument and returns a reference
to an object that contains some information obtained from the file: FData
&ReadFile(strin g FilePath);

But , for example, when the file doesnt exists, i should not return any
reference to a bad constructed object, so i need something as a NULL
reference object. I suppose i could return a pointer instead, but i have
some code written with references which I´d like to preserve...


You have a number of choices. First of all, I have to wonder why you're
returning a reference at all -- almost the only time you want a function
to return a reference is when it's returning a reference to an object
that was passed to it as a parameter (e.g. operator= return *this, or
operator<< or operator>> returning a reference to the stream in which it
was invoked).

If you insist on doing this anyway, one possibility is to create a
static instance of an object and return a reference to it when you need
a null object:

class FData {
public:
static FData null_object;
// ...
};

FData::null_obj ect;

FData &ReadFile(strin g const &FilePath) {
// I know access isn't portable, but hopefully I can get away with it as
// filling, so to speak.
if ( !access(FilePat h.c_str(), 0))
return FData::null_obj ect;
// ...
}

Using this implicitly assumes that the object in question is relatively
small -- if an object takes up a lots of space, you probably don't want
to create one just to use as a null object. This allows you to use
references, but having introduced the possibility of a null object being
returned, your code usually has to be written a lot like if you used
pointers -- instead of 'if ( returned_value == NULL)', you use something
like 'if (&returned_valu e == &FData::null_ob ject)', but the basic form
of the code becomes almost like you used pointers.

You've already mentioned the possibility of using pointers, and (more or
less) rejected it.

Another possibility would be for ReadData to throw an exception if it
can't do what it's been asked to. Normally I wouldn't suggest this for
dealing with a situation like a missing file, but if it allows you to
write the rest of your code a lot more cleanly, it may be justified.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 19 '05 #7
In article <MP************ ************@ne ws.clspco.adelp hia.net>,
jc*****@taeus.c om says...

[ ... ]
FData::null_obj ect;


Oops -- that should be:

FData FData::null_obj ect;

My apologies for the screw-up.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 19 '05 #8

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

Similar topics

13
3099
by: Don Vaillancourt | last post by:
What's going on with Javascript. At the beginning there was the "undefined" value which represented an object which really didn't exist then came the null keyword. But yesterday I stumbled across "null" string. I know that I will get an "undefined" when I try to retrieve something from the DOM which doesn't exist. I have used null myself to initialize or reset variables. But in which
14
3174
by: MuZZy | last post by:
Hi, Lately i've been (and still am) fixing some memory leaks problems in the project i just took over when i got this new job. Among the other issues i've noticed that for localy created objects it makes difference to explicitly put them to null after working with them is done - it somehow makes the GC collect them sooner, like here: void SomeFunc() { MyClass c = new MyClass();
4
2766
by: Peter Hemmingsen | last post by:
Hi, I have a dotnet object (implemented in mc++ and used in c#) which have a property called "Info". The Info property is also a dotnet object (implemented in mc++). In the constructor of the "main" object I want to initialize the property "Info" to null in a way that will make the c# programmer (the user) able to write: if (MyObj.Info==null) {..}
2
2903
by: Anastasios Papadopoulos | last post by:
Hello all, I have statements like the following in my Property Get: Public Property AccountNumber() As String Get Return MyClass.AccountNumber.ToString End Get blah blah End Property
6
9807
by: marcwentink | last post by:
Dear Sirs, Dear Newsgroup, Imagine I have some function that only gives me an iterator to a vector, but not the vector itself. Unfortunately this vector can be empty and the iterator can point to 'non valid'. Yes I know this is rather silly, but I did not write the code... Normally I know you would check for "iterator != vector.end()", but since I do not seem to have the vector without changing a lot of old
5
1926
by: rengeek33 | last post by:
I am building a SQL statement for Oracle and need one part of it to read: , myvar = null, myvar2 = "1", myvar3 = "0", myvar4 = null, etc. I am constructing this string using the String object with the following code: theSQL.Append(" , myvar = " & FormatValue(MyClass.DB_CHAR1, Me.MyVar))
5
2289
RMWChaos
by: RMWChaos | last post by:
I am working on a script to create and remove DOM elements, and I want to make it as efficient as possible (no redundancies). Because DOM elements each have their own set of attributes, the function variable list is quite long, and each type of element may not use some of the variables. As a placeholder, I use "null" when there is no value, but this can result in lots of "null" values. So I want to create a function to autofill the "null"...
3
7321
by: phub11 | last post by:
Hi all, I have a routine that checks to see if an ID has been set for the next row down in a table. Everything works fine except if I'm on the last row and no row exists; the routine just hangs: var checkNext = obj.parentNode.parentNode.nextSibling.id; Any ideas how I can get this to return "null" or "false" is there isn't a subsequent row in the table?
0
9928
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9776
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
10718
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
10816
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
10402
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
9555
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
5781
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4597
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
3225
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.