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

return value by reference

hi all

In what condition i need( or mast) a (templates)function return value by
reference?

can you give me a example

thanks
Oct 24 '06 #1
12 2065
"huangshan" <hu**************@hotmail.comwrote:
In what condition i need( or mast) a (templates)function return value by
reference?

can you give me a example
If I understand the question, have it return by reference when what it
is returning is something that the calling code legitimately already has
access to (e.g.; something that was passed to it as a reference
parameter, or when it's returning '*this',) or when it's a
member-function and the class guarantees that the object returned will
exist at least until the next member-function is called (make it return
a const reference in this case.)

--
To send me email, put "sheltie" in the subject.
Oct 24 '06 #2
class1& function1()
{
class1* c=new class1;
return *c;
}

huangshan wrote:
hi all

In what condition i need( or mast) a (templates)function return value by
reference?

can you give me a example

thanks
Oct 24 '06 #3

huangshan wrote:
hi all

In what condition i need( or mast) a (templates)function return value by
reference?

can you give me a example

thanks
If you had provided a simple example - the exercise would have been far
more relevent for you.
Template or not, the exact same rules apply.

The "conditions" are
a) that the object/variable returned must be valid (not destroyed)
b) when is a reference, or a const reference, required?

Lets take an example and perhaps dispell what "returning" means:
void increment(int& r_n)
{
++r_n;
}

This function looks like its not returning anything, but it actually is
in the sense that its modifying a supplied parameter, not a *local*
copy of that parameter. So "returning" a reference is often safely
accomplished by having a reference as a parameter.

int& increment(int n) // bad code
{
return n;
}
That function is undefined behavious since integer n (a local copy)
ceases to exist when the function returns. Returning a reference to
garbage is garbage (TM).

Finally, and perhaps a tad more relevent, a *const* reference is the
safe way to return a private member of a class - safely. In this case,
obviously, n is valid but the goal here is not to allow somebody to
accidentally modify the private member via get() - just because they
have a reference to it.

template< typename T >
class N
{
T t;
public:
N() : t() { }
const T& get() const { return t; }
};

Its important to note that the const specifiers are very important
here. If you were to implement get() without the const specifiers,
you'ld be able to something nasty like get() = 6 and accidentally
modify member t through the reference - very,very bad side effect.
So its not just about "when returning a reference is valid" anymore but
rather "when does it make sense" to return what type of reference
(const or not?).

Oct 24 '06 #4
On 23 Oct 2006 20:00:33 -0700 in comp.lang.c++, co*******@gmail.com
wrote,
>class1& function1()
{
class1* c=new class1;
return *c;
}
A reference to dynamic data that the caller will eventually have to
turn back into a pointer so that he can delete it? Can there be a
worse example?

Oct 24 '06 #5
[rearranged - please don't top post]
huangshan wrote:
hi all

In what condition i need( or mast) a (templates)function return value by
reference?

can you give me a example

thanks
co*******@gmail.com wrote:

template< typename class1 >
class1& function1()
{
class1* c=new class1;
return *c;
}
The above is probably a memory leak since the compiler has no
*guarenteed* way to recover that allocation. You should not show people
a new without supplying its delete anyways, specially an OP that is
having issues with undefined behaviour. Remember that the returned
reference can be used to assign or copy a completely unrelated instance
of myclass1 - thats a disaster because you've lost any hope to
deallocate.

The only way that such an allocation would be recoverable is by *only*
allowing a reference to be initialized - which cannot be guarenteed or
enforced by function1 in any way. You also have smart pointers
available - but that raises a whole set of new questions.
Change the code in main() below to assign a variable instead of a
reference and observe the output - and the compiler's diagnostic.

template< typename class1 >
class1& function1() // bad code - don't do this
{
class1* p = new class1;
std::cout << "p = " << p << std::endl;
return *p;
}

int main()
{
int& r_n(function1< int >());
int* p_n = &r_n;
std::cout << "p_n = " << p_n << std::endl;
delete p_n;

return 0;
}

/*
p = 0x501010
p_n = 0x501010 // // ok, but only valid if r_n is a reference
*/

We all make mistakes, i more often than others, but at least check your
code before posting.

Oct 24 '06 #6

"Salt_Peter" <pj*****@yahoo.comwrote in message
news:11********************@i42g2000cwa.googlegrou ps.com...
[rearranged - please don't top post]

template< typename class1 >
class1& function1() // bad code - don't do this
{
class1* p = new class1;
std::cout << "p = " << p << std::endl;
return *p;
}

int main()
{
int& r_n(function1< int >());
int* p_n = &r_n;
std::cout << "p_n = " << p_n << std::endl;
delete p_n;

return 0;
}

/*
p = 0x501010
p_n = 0x501010 // // ok, but only valid if r_n is a reference
*/

#include <iostream>
using namespace std;

template< typename class1 >
class1& function1() // bad code - don't do this
{
class1* p = new class1;
std::cout << "p = " << p << std::endl;
return *p;
}
int main()
{
int* p_n = &function1< int >();
std::cout << "p_n = " << p_n << std::endl;
delete p_n;
system("pause");
return 0;
}

I modify your code as above,
are they same with your code?

i think they are same.
Oct 24 '06 #7
A reference to dynamic data that the caller will eventually have to
turn back into a pointer so that he can delete it? Can there be a
worse example?
That's not too bad. A worse example can be:

class1& function2()
{
static class1 c1

if (function3())
return c1;

return *(new class1);
}
Oct 24 '06 #8
benben posted:
That's not too bad. A worse example can be:

class1& function2()
{
static class1 c1

if (function3())
return c1;

return *(new class1);
}
<sarcasm>

Don't forget the obligatory global:

bool should_delete = false;

Class1 &Func2()
{
static Class1 obj;

if (Func3()) { should_delete = false; return obj; }

should_delete = true; return *new Class1;
}

</sarcasm>

--

Frederick Gotham
Oct 24 '06 #9
Salt_Peter posted:
template< typename class1 >
>class1& function1()
{
class1* c=new class1;
return *c;
}

The above is probably a memory leak since the compiler has no
*guarenteed* way to recover that allocation.

Where there's a will, there's a way. . .

(Unchecked code)

template<class T>
void TypeSpecificDelete(void const *const p)
{
delete static_cast<T const*>(p);
}

struct PtrWithDel {
void const *p;
void (*Deletor)(void const*);
};

template<typename class1>
PtrWithDel function1()
{
PtrWithDel const a = { new class1, TypeSpecificDelete<class1};

return a;
}

--

Frederick Gotham
Oct 24 '06 #10

huangshan wrote:
"Salt_Peter" <pj*****@yahoo.comwrote in message
news:11********************@i42g2000cwa.googlegrou ps.com...
[rearranged - please don't top post]

template< typename class1 >
class1& function1() // bad code - don't do this
{
class1* p = new class1;
std::cout << "p = " << p << std::endl;
return *p;
}

int main()
{
int& r_n(function1< int >());
int* p_n = &r_n;
std::cout << "p_n = " << p_n << std::endl;
delete p_n;

return 0;
}

/*
p = 0x501010
p_n = 0x501010 // // ok, but only valid if r_n is a reference
*/


#include <iostream>
using namespace std;

template< typename class1 >
class1& function1() // bad code - don't do this
{
class1* p = new class1;
std::cout << "p = " << p << std::endl;
return *p;
}
int main()
{
int* p_n = &function1< int >();
BAD idea. Its dangerous code. even if int const * const was used.
std::cout << "p_n = " << p_n << std::endl;
What if the pointer was modified to point elsewhere here?
delete p_n;
system("pause");
return 0;
}

I modify your code as above,
are they same with your code?

i think they are same.
No, its not the same and just as BAD.

You are a programmer and YOU have responsabilities. One of those
responsabilities is to write code that is relatively safe. That means
you must enforce how clients use your classes and functions in such a
way that regardless what they throw at it, regardless how they use it,
the result is expected and relatively well defined. And that client,
one day, may very well be you.

One does not new over here and then delete overthere - that, on the
outset, breaks a fundamental rule. Allocation and deallocation is not
something you distribute or give away.

The fact that function1 allows assignment/copy to a variable is enough
to consign such code to the recycle bin. Writing code like the above is
dangerous, down-right unprofessional and guarenteed to generate bugs
down the line.

Oct 24 '06 #11

Frederick Gotham wrote:
Salt_Peter posted:
template< typename class1 >
class1& function1()
{
class1* c=new class1;
return *c;
}
The above is probably a memory leak since the compiler has no
*guarenteed* way to recover that allocation.


Where there's a will, there's a way. . .
yes there is. see below.
>
(Unchecked code)
--

Frederick Gotham
template<class T>
void TypeSpecificDelete(void const *const p)
{
delete static_cast<T const*>(p);
}

struct PtrWithDel {
void const *p;
void (*Deletor)(void const*);
};

template<typename class1>
PtrWithDel function1()
{
PtrWithDel const a = { new class1, TypeSpecificDelete<class1};

return a;
}
back to the basics...

#include <iostream>

template< typename N >
struct Capsule
{
Capsule() : n() { std::cout << "Capsule()\n"; }
Capsule(N& x) : n(x) { std::cout << "Capsule()\n"; }
~Capsule() { std::cout << "~Capsule()\n"; }
const N& function1() const { return n; } // <- our protagonist
private:
N n;
};

int main()
{
Capsule<intinstance;
int n = instance.function1();
const int& r_n = instance.function1();
const int * const p_n = &instance.function1();

return 0;
}

.... and no heap allocation needed.

Oct 24 '06 #12
hello

thank you

now ,i know it is bad code like :
>>class1& function1() // bad code - don't do this
{
class1* p = new class1;
std::cout << "p = " << p << std::endl;
return *p;
}
i just want to know how different betwen
int& r_n(function1< int >());
int* p_n = &r_n;
and
int* p_n = &function1< int >();

Oct 25 '06 #13

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

Similar topics

8
by: DaKoadMunky | last post by:
Please consider the following... <CODE> #include <string> using namespace std; typedef int PrimitiveType; typedef string ClassType;
14
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...
5
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)...
12
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
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 =...
2
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 {
9
by: Samuel Shulman | last post by:
Hi I wander there is a way to return ByRef just like passing ByRef What I want to achieve is the following: Call a method that returns an object Use that call as an argument to a ByRef...
4
by: Zytan | last post by:
It seems I cannot return a reference to a value type as the return value of a method. I will have to use an out parameter instead. Is there another way to do it? Zytan
9
by: mtczx232 | last post by:
it's posible that Function return byref? what the syntax?
10
by: flopbucket | last post by:
Hi, Is this legal? std::string foo() { std::string xyz = "FOO"; return xyz; }
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: 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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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,...
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...

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.