473,856 Members | 1,571 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to return by reference?

I know the below code is wrong:

Object & test(){ return Object() ;}
Object & v = test() ;

the Object is just a temporary variable,
so you the variable may be reference to
nothing.

And I try to this:

Object & test () { return * new Object(); }
Object & v = test () ;

But how can I destroy the Object's memery?

But, how to return reference safely?
Is there any principle to return by reference?
Nov 29 '06 #1
6 1923
Bo Yang napsal:
I know the below code is wrong:

Object & test(){ return Object() ;}
Object & v = test() ;

the Object is just a temporary variable,
so you the variable may be reference to
nothing.

And I try to this:

Object & test () { return * new Object(); }
Object & v = test () ;

But how can I destroy the Object's memery?

But, how to return reference safely?
Is there any principle to return by reference?
By reference is usually returned
(1) *this (typically in overloaded operator=) or
(2) some class member instance or
(3) instance stored in some container

The main rule is "Instance must not be local variable of function,
which returns reference to it.

class Test
{
public:
Test(int data): data_(data) { }

// This example for case (1)
Test& operator=(const test& src)
{
data_ = src.data_;
return *this;
}

// This is example for case (2)
int& GetData() { return data_; }
};

Nov 29 '06 #2

Bo Yang wrote:
I know the below code is wrong:

Object & test(){ return Object() ;}
Object & v = test() ;

the Object is just a temporary variable,
so you the variable may be reference to
nothing.

And I try to this:

Object & test () { return * new Object(); }
Object & v = test () ;

But how can I destroy the Object's memery?
delete & v;

means delete the variable that v is a reference to which is the
unnamed Object created in test();

But, how to return reference safely?
Is there any principle to return by reference?
Usually you will also pass the object into the function by reference:

class Object{};
Object & test(Object &);
Object o;

Object & v = test(o);

v is 'another name' for o;

regards
Andy Little

Nov 29 '06 #3
Ondra Holub :
Bo Yang napsal:
>I know the below code is wrong:

Object & test(){ return Object() ;}
Object & v = test() ;

the Object is just a temporary variable,
so you the variable may be reference to
nothing.

And I try to this:

Object & test () { return * new Object(); }
Object & v = test () ;

But how can I destroy the Object's memery?

But, how to return reference safely?
Is there any principle to return by reference?

By reference is usually returned
(1) *this (typically in overloaded operator=) or
(2) some class member instance or
(3) instance stored in some container

The main rule is "Instance must not be local variable of function,
which returns reference to it.
And when I implement a '-' operator in a class,
I must to do

Test & operator -( Test & right ) ;

How to implement this function then ?
I must to new a Test in this function , mustn't I ?
>
class Test
{
public:
Test(int data): data_(data) { }

// This example for case (1)
Test& operator=(const test& src)
{
data_ = src.data_;
return *this;
}

// This is example for case (2)
int& GetData() { return data_; }
};
Nov 29 '06 #4

Bo Yang wrote:
I know the below code is wrong:

Object & test(){ return Object() ;}
Object & v = test() ;

the Object is just a temporary variable,
so you the variable may be reference to
nothing.

And I try to this:

Object & test () { return * new Object(); }
Object & v = test () ;

But how can I destroy the Object's memery?

But, how to return reference safely?
Is there any principle to return by reference?
you can return Object by value

Object test(){ return Object(); }

and then bind the return to reference on use

Object & obj = test();

If carefull, you can avoid copying

or, if Object is too big for stack, use

std::auto_ptr<O bjecttest(){ return std::auto_ptr<O bject>(new Object);
}

Nov 29 '06 #5
Bo Yang wrote:
>By reference is usually returned
(1) *this (typically in overloaded operator=) or
(2) some class member instance or
(3) instance stored in some container

The main rule is "Instance must not be local variable of function,
which returns reference to it.

And when I implement a '-' operator in a class,
I must to do

Test & operator -( Test & right ) ;
Usually, you let that operator take a const reference as argument and return
an object instead of a reference.
How to implement this function then ?
I must to new a Test in this function , mustn't I ?
No. Well, you can, but shouldn't. You simply don't return by reference.

Nov 29 '06 #6
Rolf Magnus :
Bo Yang wrote:
>>By reference is usually returned
(1) *this (typically in overloaded operator=) or
(2) some class member instance or
(3) instance stored in some container

The main rule is "Instance must not be local variable of function,
which returns reference to it.
And when I implement a '-' operator in a class,
I must to do

Test & operator -( Test & right ) ;

Usually, you let that operator take a const reference as argument and return
an object instead of a reference.
I have take a look at the FAQ and found
the return type is usually a value but a reference.
I understand the principle, return by reference only
if the object you return is all at your control.

Thank you!
>
>How to implement this function then ?
I must to new a Test in this function , mustn't I ?

No. Well, you can, but shouldn't. You simply don't return by reference.
Nov 29 '06 #7

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

Similar topics

3
28133
by: Wang Tong | last post by:
Suppose I have a function foo() and a class definition myClass, and I want to create an instance of myClass and return it from foo(). I guess the most efficient way is to return a reference to the object. But here comes the problem: the object is a local one and will be detroyed after function return. How can I return the reference from foo()? Code: myClass& foo()
3
1603
by: Zork | last post by:
Hi, I am a little confused with const functions, for instance (here i am just overloading the unary+ operator) if i define: 1) Length Length :: operator+ ( void ) const {return * this;} ... I get no error... 2) Length & Length :: operator+ ( void ) const {return * this;} ... I get the error -> 'return' : cannot convert from 'const class Length' to
5
3765
by: klaus triendl | last post by:
hi, recently i discovered a memory leak in our code; after some investigation i could reduce it to the following problem: return objects of functions are handled as temporary objects, hence their dtor is called immediately and not at the end of the function. to be able to use return objects (to avoid copying) i often assign them to a const reference. now, casting a const return object from a function to a non-const reference to this...
25
4155
by: cppaddict | last post by:
I'd like to know what goes on under the hood when methods return objects. Eg, I have a simple Point class with two members _x and _y. It's constructor, copy constructor, assignment operator and additon operator (which returns another Point object, and which my question is about) are as follows: Point::Point(int x, int y) : _x(x), _y(y) { }
14
2056
by: Gama Franco | last post by:
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.
5
3050
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
12
4140
by: Jose Fernandez | last post by:
Hello. I'm building a web service and I get this error. NEWS.News.CoverNews(string)': not all code paths return a value This is the WebMethod public SqlDataReader CoverNews(string Sport) {
20
7029
by: weston | last post by:
I've got a piece of code where, for all the world, it looks like this fails in IE 6: hometab = document.getElementById('hometab'); but this succeeds: hometabemt = document.getElementById('hometab'); Has anyone ever seen anything like this before, or am I dreaming?
2
2371
by: Eric Lilja | last post by:
Hello, consider this complete program: #include <iostream> #include <string> using std::cout; using std::endl; using std::string; class Hanna {
12
2120
by: huangshan | last post by:
hi all In what condition i need( or mast) a (templates)function return value by reference? can you give me a example thanks
0
9921
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
9765
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
11065
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
10700
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
10795
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
9536
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
5962
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4581
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
3203
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.