473,399 Members | 3,603 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,399 software developers and data experts.

Returning structures

What is the best way to create functions that, based on some input,
return either structures or a null value if the structure cannot be
made?

The problem is that the structure has be created inside the function,
and I've heard that returning a pointer to a locally created structure
is unsafe.

--
I am only a mirage.
Jul 22 '05 #1
11 2037
"kelvSYC" <ke*****@no.email.shaw.ca> wrote...
What is the best way to create functions that, based on some input,
return either structures or a null value if the structure cannot be
made?

The problem is that the structure has be created inside the function,
and I've heard that returning a pointer to a locally created structure
is unsafe.


Correct. But returning a pointer to a dynamically created structure
is perfectly fine. Just make sure that the caller disposes of it
correctly when they don't need it any longer.

SomeStruct* func() {
...
SomeStruct* toreturn = 0;
if (everything_is_OK)
toreturn = new SomeStruct(arguments);
...
return toreturn;
}

void foo() {
SomeStruct* pSS = func();
if (pSS) {
// do something
delete pSS;
}
}

Victor
Jul 22 '05 #2
kelvSYC wrote:
What is the best way to create functions that, based on some input,
return either structures or a null value
if the structure cannot be made?

The problem is that the structure has be created inside the function,
and I've heard that returning a pointer to a locally created structure
is unsafe.


struct X { /* . . . */ };

X f(void) {
X x;
// modify x
return x;
}

This is the safest *and* most efficient way.
You can invoke it like this:

X x = f();

and *no* copies will be required if your C++ compiler implements
the Named Return Value Optimization (NRVO).

Jul 22 '05 #3
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote...
kelvSYC wrote:
What is the best way to create functions that, based on some input,
return either structures or a null value
if the structure cannot be made?

The problem is that the structure has be created inside the function,
and I've heard that returning a pointer to a locally created structure
is unsafe.


struct X { /* . . . */ };

X f(void) {
X x;
// modify x
return x;
}

This is the safest *and* most efficient way.
You can invoke it like this:

X x = f();

and *no* copies will be required if your C++ compiler implements
the Named Return Value Optimization (NRVO).


What about the requirement to return something different (like 0)
to indicate the object creation is impossible?

Do you actually read the posts you reply to?

V
Jul 22 '05 #4
Victor Bazarov wrote:
What about the requirement to return something different (like 0)
to indicate the object creation is impossible?

Do you actually read the posts you reply to?


Of course I do.
And I read your response which answered kelvSYC's question very well.

But I think that I gave the OP better advice.

Jul 22 '05 #5
kelvSYC <ke*****@no.email.shaw.ca> wrote in message news:<050220041256451981%ke*****@no.email.shaw.ca> ...
What is the best way to create functions that, based on some input,
return either structures or a null value if the structure cannot be
made?

The problem is that the structure has be created inside the function,
and I've heard that returning a pointer to a locally created structure
is unsafe.


Then don't return a pointer;

struct SimpleStruct {
bool valid;
string name;
//add more
}

SimpleStruct function_returns_ss(const string &name) {
SimpleStruct dummy;
if (name == "") dummy.valid = false;
else {
dummy.name = name;
dummy.valid = true;
}

return dummy;
}

int main() {
string name_given;

//prompt for name
cout << "Name: ";
cin >> name_given;

SimpleStruct rslt;
rslt = function_return_ss(name_given);
switch (rslt.valid) {
case false: cout << "no name...\n"; break;
case true: //..... do stuff.........
}

//.... do other stuff......

return 0;
}

This is the first solution that came to my mind. I know there's a
better one but it's too early for me to think of one ;)
Jul 22 '05 #6
"kelvSYC" <ke*****@no.email.shaw.ca> wrote in message
news:050220041256451981%
What is the best way to create functions that, based on some input,
return either structures or a null value if the structure cannot be
made?

The problem is that the structure has be created inside the function,
and I've heard that returning a pointer to a locally created structure
is unsafe.


Of course the easy solution is to document that your function may return a
new object, and that the caller ought to delete the object through delete,
free, or whatever is appropriate.

But you'll still get memory leaks as your program grows, because sooner or
later someone will screw up and forget to delete something.

So consider using a smart pointer like boost::shared_ptr or std::auto_ptr.
There's lots written about smart pointers. Search this newsgroup or the
internet, buy a book, etc.

And finally, you could return an object, and throw an exception to indicate
failure. Make sure to document the fact that your class may throw this or
that exception, but preferrably without exception specifications.

--
+++++++++++
Siemel Naran
Jul 22 '05 #7
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message
X f(void) {
X x;
// modify x
return x;
}

This is the safest *and* most efficient way.
You can invoke it like this:

X x = f();

and *no* copies will be required if your C++ compiler implements
the Named Return Value Optimization (NRVO).


Most compilers don't support this optimization at the present time. But one
could always move the body of f() and its function arguments, if any, into
the constructor X::X().

--
+++++++++++
Siemel Naran
Jul 22 '05 #8
kelvSYC <ke*****@no.email.shaw.ca> wrote in message news:<050220041256451981%ke*****@no.email.shaw.ca> ...
What is the best way to create functions that, based on some input,
return either structures or a null value if the structure cannot be
made?

The problem is that the structure has be created inside the function,
and I've heard that returning a pointer to a locally created structure
is unsafe.


Well, you could for example create your structure outside the
function, and pass it as out parameter to the function with your
inputs.

boolean function (struct & struct, input1, input2, ...)
{
//There, fill in struct with inputs
....
}

If the structure cannot be made, simply return true (or false, as
preferred).
Jul 22 '05 #9
Eric Entressangle wrote:
Well, you could for example create your structure outside the
function, and pass it as out parameter to the function with your
inputs.

boolean function (struct & struct, input1, input2, ...)
{
//There, fill in struct with inputs
...
}

If the structure cannot be made, simply return true (or false, as
preferred).


Actually, this solution is the best for me for these reasons :

- Having news and deletes in different scopes is very hard to maintain.
- Having a dynamic creation as it may not be required is bad ©.

With this solution, you could make a new or a static creation (as you
wish) and let the function "build" your structure. Then you could delete
it when job is done.

OT: And boolean does not exist in C++, only bool :-).

--
Anubis
Jul 22 '05 #10
> > > What is the best way to create functions that, based on some input,
return either structures or a null value
if the structure cannot be made?

The problem is that the structure has be created inside the function,
and I've heard that returning a pointer to a locally created structure
is unsafe.


struct X { /* . . . */ };

X f(void) {
X x;
// modify x
return x;
}

This is the safest *and* most efficient way.
You can invoke it like this:

X x = f();

and *no* copies will be required if your C++ compiler implements
the Named Return Value Optimization (NRVO).


What about the requirement to return something different (like 0)
to indicate the object creation is impossible?


The OP specified an impossible combination of events. There are
(to my mind) 3 ways of resolving this:
1) relax the requirement for a struct to be returned
2) relax the requirement for NULL to be returned
3) return both in a std::pair<> or similar

Trollsdale answered number (2) with (surprisingly) a mostly
correct answer, if you ignore his extraneous use of
the dereference operator.

One could augment his answer by giving X a flag, or some such,
indicating whether there was an error condition.

Note that the OP's other requirement "if a structure cannot be made"
is also unlikely, because either a struct is constructible
or it isn't (perhaps the OP meant, "if some error condition occurs").

Other posters on the the thread have answered (1) (with suggestions
like returning a pointer, or filling out a reference-to-struct
passed as parameter).
Jul 22 '05 #11
Old Wolf wrote:
The OP specified an impossible combination of events. There are
(to my mind) 3 ways of resolving this:
1) relax the requirement for a struct to be returned
2) relax the requirement for NULL to be returned
3) return both in a std::pair<> or similar


Actually there is another option, modifying the needs.

Yes, returning a structure OR null is impossible. But what do you think
the OP will choose between forgetting one functionnality or modifying one ?

Choosing between not returning a structure or returning a structure by
reference parameter instead of return is an easy choice I think.

--
Anubis
Jul 22 '05 #12

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

Similar topics

6
by: Generic Usenet Account | last post by:
Is it okay to return a local datastructure (something of type struct) from a function, as long as it does not have any pointer fields? I think it is a bad idea, but one of my colleagues does not...
9
by: CptDondo | last post by:
I am working on an embedded platform which has a block of battery-backed RAM. I need to store various types of data in this block of memory - for example, bitmapped data for control registers,...
8
by: MyAlias | last post by:
Can't solve this CallBack returning structures Error message: An unhandled exception of type 'System.NullReferenceException' occurred in MyTest.exe Additional information: Object reference not...
5
by: Robert Fitzpatrick | last post by:
Can someone point me to some more information or perhaps show an example of returning a recordset from a plpgsql function. I'd like to send an argument or arguments to the function, do some queries...
4
by: Daniel | last post by:
I've been asking around and reading but I cannot find a definitive answer. I have customers that need information from our calendar application. The data will come from SQL Server 2000. The...
15
by: Joseph Geretz | last post by:
I'm a bit puzzled by the current recommendation not to send Datasets or Datatables between application tiers. http://support.microsoft.com/kb/306134 ...
2
by: =?Utf-8?B?dmxhZGltaXI=?= | last post by:
Hi, i have big subsystem written in old C and published by dll (and lib). Dll functions do: 1) allocate global memory for internal structures 2) controls dll subsystem (communicate by sockets,...
17
by: daniel | last post by:
Hello , How safe is it to return a structure from a function. Let's say we have the following situation: typedef struct MyStruct{ int a;
160
by: DiAvOl | last post by:
Hello everyone, Please take a look at the following code: #include <stdio.h> typedef struct person { char name; int age; } Person;
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: 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
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
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...
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...
0
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...

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.