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

returning a reference

Trying to avoid a temp object, and c-style funcitons
(i.e., void doSomethingTo(Type* thisObject) ).

<referece: code below>

Is it safe to return a reference to an internally created object? Is
obj's destructor called at end of main or at end of fromString()?

This is how I uderstand it: o's copy constructor is called with obj as
the arg, and I have avoided a temporary instance of Object.

Is this safe?

Thanks

<code>
class Object
{
public:
static Object &fromString(std::string str)
{
Object obj;
//process string, and set attributes of obj
return obj;
}
};

int main()
{
Object o = Object::fromString("attribute1,attribute2");
cout << "att1 is " << o.getAtt1()
<< "att2 is " << o.getAtt1()
<< "att3 is " << o.getAtt1() << endl;
}
</code>

Jul 19 '05 #1
7 8127
Shea Martin wrote:
Trying to avoid a temp object, and c-style funcitons
(i.e., void doSomethingTo(Type* thisObject) ).

<referece: code below>

Is it safe to return a reference to an internally created object? Is
obj's destructor called at end of main or at end of fromString()? No. It's not safe. Destructor is called at the end of fromString().
This is how I uderstand it: o's copy constructor is called with obj as
the arg, and I have avoided a temporary instance of Object.

Is this safe?

Thanks

<code>
class Object
{
public:
static Object &fromString(std::string str) Should be: static Object fromString(std::string str) {
Object obj;
//process string, and set attributes of obj
return obj; This is ungood. obj is destroyed at the end of fromString
Scott Meyers has a good discussion of this in Effective C++, where he points
out that while return by reference is nice for efficiency, there are cases
(such as this one) where you need to return by value.
}
};

int main()
{
Object o = Object::fromString("attribute1,attribute2");
cout << "att1 is " << o.getAtt1()
<< "att2 is " << o.getAtt1()
<< "att3 is " << o.getAtt1() << endl;
}
</code>

It's essentially the equivalent of the C construct:

int *f()
{
int x;
return &x;
}

When you return from f, the pointer is invalid. Similarly, when you return from fromString, the
reference doesn't refer to anything valid.

red floyd

Jul 19 '05 #2

"Shea Martin" <sm*****@arcis.com> wrote in message
news:4JXgb.6802$f7.391628@localhost...
Trying to avoid a temp object, and c-style funcitons
(i.e., void doSomethingTo(Type* thisObject) ).

<referece: code below>

Is it safe to return a reference to an internally created object?
Sometimes.
Is obj's destructor called at end of main or at end of fromString()?
Yes. This isn't one of those times :-)
This is how I uderstand it: o's copy constructor is called with obj as
the arg, and I have avoided a temporary instance of Object.


There is no obj to use as an arg, since as you guessed it was destroyed
after leaving fromString.
Jul 19 '05 #3
Shea Martin wrote:
Trying to avoid a temp object, and c-style funcitons
(i.e., void doSomethingTo(Type* thisObject) ).
<referece: code below>

Is it safe to return a reference to an internally created object?
No.
Is obj's destructor called at end of main or at end of fromString()?
At the end of fromString().
This is how I uderstand it: o's copy constructor is called with obj
as the arg, and I have avoided a temporary instance of Object.
Wrong.
Is this safe?

Thanks

<code>
class Object
{
public:
static Object &fromString(std::string str)
You have to return an Object, not a reference. Btw, the above will copy
the std::string, so you should use a reference here:

static Object fromString(const std::string& str)

Btw, a good compiler optimzies the extra copy of function return values
away.
{
Object obj;
//process string, and set attributes of obj
return obj;
}
};

int main()
{
Object o = Object::fromString("attribute1,attribute2");
cout << "att1 is " << o.getAtt1()
<< "att2 is " << o.getAtt1()
<< "att3 is " << o.getAtt1() << endl;
}
</code>


Jul 19 '05 #4

"Rolf Magnus" <ra******@t-online.de> wrote in message
news:bm*************@news.t-online.com...
static Object &fromString(std::string str)


You have to return an Object, not a reference.


You can return a reference as long as the object is allocated dynamically.
This puts the responsibility for the object (deletion) with the caller.
Jul 19 '05 #5
> Trying to avoid a temp object, and c-style funcitons
(i.e., void doSomethingTo(Type* thisObject) ).
Good idea, but sometimes you can't.
<referece: code below>

Is it safe to return a reference to an internally created object?
No.
Is
obj's destructor called at end of main or at end of fromString()?
Yes, when it gets out of scope, it is destroyed.
This is how I uderstand it: o's copy constructor is called with obj as
the arg, and I have avoided a temporary instance of Object.
It didn't have the time! 'obj' was destroyed before 'o' was ever aware
of its existence.
Is this safe?
No! 'Well it works on my computer'. That's bad since you'll have a lot of
troubles finding why it crashes 5 minutes (or an hour) after. This would
be called undefined behavior.
<code>
class Object
{
public:
static Object &fromString(std::string str)
Never, never return a reference to something if that something did not exist
prior entering a function (except for dynamically allocated memory, but then
I hope you'll go for pointers.
{
Object obj;
'obj' is created here.
//process string, and set attributes of obj
return obj;
}
'obj' is destroyed there.
};

int main()
{
Object o = Object::fromString("attribute1,attribute2");


fromString() returns a reference to an already destroyed object.
Undefined behavior. Don't do that!

When you want to return a object which was inexistant, do it
by value. You have got no other choices (except for dynamically
allocated memory, which is always something to avoid).
Jonathan


Jul 19 '05 #6

"Jonathan Mcdougall" <jo***************@DELyahoo.ca> wrote in message
news:cf*********************@weber.videotron.net.. .
public:
static Object &fromString(std::string str)
Never, never return a reference to something if that something did not

exist prior entering a function (except for dynamically allocated memory, but then I hope you'll go for pointers.


Why would you recommend pointers rather than references in that case?
Jul 19 '05 #7
> > > public:
static Object &fromString(std::string str)


Never, never return a reference to something if that something did not

exist
prior entering a function (except for dynamically allocated memory, but

then
I hope you'll go for pointers.


Why would you recommend pointers rather than references in that case?


Because it makes more sense :

int &f()
{
return *new int;
}

int *g()
{
return new int;
}
int main()
{
int &a = f();
int *b = g();

delete &a; // yurk
delete b;
}
Jonathan
Jul 19 '05 #8

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

Similar topics

6
by: Krackers | last post by:
How do you write a function which returns a reference to an array. I can only get a function to return a copy of the array itself. I've had a look at some other threads in this group an the return...
9
by: mjm | last post by:
Folks, Stroustrup indicates that returning by value can be faster than returning by reference but gives no details as to the size of the returned object up to which this holds. My question is...
7
by: Pablo J Royo | last post by:
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(string FilePath); But ,...
11
by: JKop | last post by:
AnyClass Blah() { AnyClass poo; return poo; } As we all know, in the above, the compiler is entitled to:
10
by: Fraser Ross | last post by:
I need to know the syntax for writing a reference of an array. I haven't seen it done often. I have a class with a member array and I want a member function to return an reference to it. ...
3
by: Faustino Dina | last post by:
Hi, The following code is from an article published in Informit.com at http://www.informit.com/guides/content.asp?g=dotnet&seqNum=142. The problem is the author says it is not a good idea to...
6
by: EvilOldGit | last post by:
const Thing &operator++(int) { Thing temp = *this; operator++(); return temp; } Is this code robust ? I get a compiler warning about returning a reference to a a local, which I guess is...
7
by: Thomas Lenz | last post by:
Please consider the following code snippet: string myfunction() { ostringstream oss; oss << "junk"; // do something more with oss; I can't make it const... return oss.str(); } Is the...
23
by: pauldepstein | last post by:
Below is posted from a link for Stanford students in computer science. QUOTE BEGINS HERE Because of the risk of misuse, some experts recommend never returning a reference from a function or...
8
by: darren | last post by:
Hi everybody, have a quick look at this code: ===== ===== int main(void) { string msg; makeString(msg); cout << "back in main, result = " << msg << endl;
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...

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.