473,549 Members | 2,592 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2048
"kelvSYC" <ke*****@no.ema il.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(argu ments);
...
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.ema il.shaw.ca> wrote in message news:<050220041 256451981%ke*** **@no.email.sha w.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_return s_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.ema il.shaw.ca> wrote in message
news:0502200412 56451981%
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_p tr 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.ema il.shaw.ca> wrote in message news:<050220041 256451981%ke*** **@no.email.sha w.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

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

Similar topics

6
2413
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 seem to think so. According to my colleague, if the data structure does not "deep copy" issues, it is perfectly okay to return a local variable. ...
9
2419
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, strings for logging, and structures for data points. I want to use one function to read data from this block and one function to write data, for...
8
1826
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 set to an instance of an object. Situation skeleton: Private Declare Function EnumFontFamiliesASCII Lib "gdi32" Alias
5
14311
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 to return a set of records. I've done several functions that return one value of one type, but nothing that returns a set. -- Robert
4
1218
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 customers who use .net are able to read the datasets that the web service returns. I'm having problems when customers are using Java or CFMX. What...
15
13487
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 http://msdn2.microsoft.com/en-us/library/ms996381.aspx Formerly, with classic Microsoft DNA architecture, the ADO Recordset was a primary transport medium, recommended for transmitting data...
2
1903
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, read a files, etc). These control functions triggers change of a values in the subsystem internal structures. 3) dealocate memory for internal...
17
1671
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
5771
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
7726
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. ...
0
7967
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...
1
7485
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...
0
6052
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...
0
5097
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...
0
3505
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...
1
1953
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
1
1064
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
772
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...

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.