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

a basic question about Object, Object&

i worte a simple code below.

------------------------------------------------------------------------------------

#include "stdafx.h"

class Object {
public:
int a;

Object() {
a = 100;
}
};

Object aFunction() {
return Object();
}

Object& bFunction() {
return Object();
}

int _tmain(int argc, _TCHAR* argv[])
{
std::cout << aFunction().a << std::endl;

std::cout << bFunction().a << std::endl;
return 0;
}

----------------------------------------------------------------------------------

as i see the two different return type, Object, Object&, do same thing.

the results are both printing 100.

but i see a warnning message from compiling this code.

what's the difference between Object and Object&?

i see Object& as a return type and an argument.

plz can anyone explain it?

thanks in advance. :)

Oct 24 '06 #1
4 1950
"gg9h0st" <mn*****@hotmail.comwrote in message
news:11**********************@b28g2000cwb.googlegr oups.com...
>i worte a simple code below.

------------------------------------------------------------------------------------

#include "stdafx.h"

class Object {
public:
int a;

Object() {
a = 100;
}
};

Object aFunction() {
return Object();
}

Object& bFunction() {
return Object();
}

int _tmain(int argc, _TCHAR* argv[])
{
std::cout << aFunction().a << std::endl;

std::cout << bFunction().a << std::endl;
return 0;
}

----------------------------------------------------------------------------------

as i see the two different return type, Object, Object&, do same thing.

the results are both printing 100.

but i see a warnning message from compiling this code.

what's the difference between Object and Object&?

i see Object& as a return type and an argument.

plz can anyone explain it?

thanks in advance. :)
Object& is a reference.
Object is an instance.

For this purpose only, think of Object& as Object*, since a reference is a
pointer on steroids.

Now look at your method:
Object& bFunction() {
return Object();
}

You are returning a refernce (pointer) to a termporary object. The problem
is, this object is going to go away very quickly, since it's only a
temporary object.

For the purpost here it's (probably) okay, since you are not trying to do
anything with it. Consider if you had done this:

Object& MyObject = bFunction();

std::cout << MyObject.a << std::endl;
That last line would probably crash with a memory error (or not, undefined
behavior). The reason is bFunction() created a temporary object and
returned a reference to it, which is stored in MyObject. After that line is
finished, the temporary goes away (if not sooner). Now MyObject is pointing
to memory that no longer (necessarily) contains an instance of Object.

Same as if you had done this:

Object* cFunction()
{
return &(Object());
}

Returning the address of a temporary variable (which is the same thing your
bFunction is doing, it's just wrapped in a refernce).

Understand?
Oct 24 '06 #2

gg9h0st wrote:
i worte a simple code below.
Are you sure you wrote it and not some automatic code generator that
comes with your compiler?
------------------------------------------------------------------------------------

#include "stdafx.h"
What's stdafx.h?
class Object {
public:
int a;

Object() {
a = 100;
}
};
Side issues: Your data member should be private and your constructor
should use an intialiser list, not assignment in the constructor body.
Object aFunction() {
That signature says that aFunction returns an object of type "Object"
by value.
return Object();
}
This statement creates an unnamed temporary object of type "Object" and
returns it. The unnamed temporary ceases to exist at the end of this
statement. Because the function returns by value, before the unnamed
temporary is destroyed, a copy is made and that copy is returned to the
function that called aFunction.
Object& bFunction() {
That signature says that bFunction returns a reference to an object of
type "Object". A reference is not the object itself, it is an alias for
the object. So the object referred to needs to exist somewhere.
return Object();
This statement creates an unnamed temporary object of type "Object" and
returns it. The unnamed temporary ceases to exist at the end of this
statement. Because the function returns by reference, the returned
reference is intialised with (and so is an alias for) this unnamed
temporary. But as soon as this statement ends, the unnamed temporary is
destroyed. The reference is returned to the function that called
bFunction, but the object to which that reference refers no longer
exists. Any attept to use that reference invokes undefined behavior.
}

int _tmain(int argc, _TCHAR* argv[])
The _tmain and _TCHAR parts of that code are not standard C++
{
std::cout << aFunction().a << std::endl;
aFunction returns an object. That object is a copy of the unnamed
temporary that was created and destroyed within aFunction. So this code
will output 100.
std::cout << bFunction().a << std::endl;
bFunction returns a reference to an object. That object referred to is
the unnamed temporary that was created and destroyed within bFunction.
Because the referred to object has been destroyed, the behaviour of
your code is undefined. Anything can happen.
return 0;
}

----------------------------------------------------------------------------------

as i see the two different return type, Object, Object&, do same thing.

the results are both printing 100.
That's because you were unlucky. The use of the return value of
bFunction invokes undefined behaviour. Anything can happen and one of
the possbilities is that the code does exaclt what you think it should
do. As far as the C++ language is concerned, the behaviour would be no
more or less correct if it printed 200 instead of 100, or if it printed
"hello world", or if it emailed "hello world" to everyone in your
address book, or if it formatted your hard drive.
but i see a warnning message from compiling this code.
Good. Your compiler may well have a setting that lets you treat
warnings as errors and so prevent successful compiling if a warning is
issued. If you can find this setting, turn it on. The compiler is your
friend. Help it to help you.
what's the difference between Object and Object&?
In your case, the latter invokes undefined behaviour, which is a Bad
Thing.
i see Object& as a return type and an argument.
http://www.parashift.com/c++-faq-lite/references.html

Gavin Deane

Oct 24 '06 #3
helps alot. greate explanation

thanks both of you. :)

Oct 24 '06 #4
gg9h0st wrote:
i worte a simple code below.

------------------------------------------------------------------------------------

#include "stdafx.h"
stdafx.h is not needed here, disable precompiled headers in your
project.
>
class Object {
public:
int a;

Object() {
a = 100;
}
};
use the init list in your ctors, the struct is just a suggestion:

struct Object
{
int a;
Object() : a(100) { }
};
>
Object aFunction() {
return Object();
}
the above returns an Object by value.
>
Object& bFunction() {
return Object();
}
the above returns a reference to a local variable (which is about be
get zapped)
>
int _tmain(int argc, _TCHAR* argv[])
int main()
{
std::cout << aFunction().a << std::endl;

std::cout << bFunction().a << std::endl;
return 0;
}

----------------------------------------------------------------------------------

as i see the two different return type, Object, Object&, do same thing.

the results are both printing 100.

but i see a warnning message from compiling this code.

what's the difference between Object and Object&?

i see Object& as a return type and an argument.

plz can anyone explain it?
When you are faced with an issue like this, equip the compiler to show
you the sequence of events.

Note how construction and destruction of the local copy happens
*before* the copy ctor is invoked in the code below. You'll say "but
its working correctly" and the standard response is: what if object_b
was itself a reference? What guarentees do you have that the remnants
of that zapped local do not get overwritten somewhere down the line?
Can you say - nasty, nasty bug? The compiler sees the remnants of the
local copy as free, available memory space just begging to be reused.

#include <iostream>

struct Object
{
int a;
Object() : a(100) { std::cout << "Object()" << std::endl; }
Object(const Object& copy)
{
a = copy.a;
std::cout << "Object(const Object& copy)" << std::endl;
};
~Object() { std::cout << "~Object()" << std::endl; }
};

const Object& bFunction()
{
return Object();
}

int main()
{
Object object_b = bFunction();
std::cout << object_b.a << std::endl;

return 0;
}

/*
Object()
~Object()
Object(const Object& copy)
100
~Object()
*/

Now change the function so it returns an Object and note what the
compiler does when it optimizes.

Object()
100
~Object()

You can add a parametized ctor to Object if you like, same result.

Oct 24 '06 #5

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

Similar topics

0
by: Chad | last post by:
I am using VB 6 and outlook 2000, I am trying to get the sender's email address from a message, but I only see the sender's name as a property. Does anyone know how to get to this information?? ...
3
by: js | last post by:
hi, how to create dao.tabledef object in asp: I need to convert the following code into asp: Dim tdf As DAO.TableDef Dim db As DAO.Database Dim fld As DAO.Field Set db =...
2
by: samir.kuthiala | last post by:
I do some requests in the background on a page using the XMLHttpRequest object. My site uses NTLM Authentication. However if the user is not logged in, it throws up an ugly dialog box. Is there...
5
by: msuk | last post by:
All, I have a VB.NET/ASP.NET application that uses some common data throughout. Now what I would like to do is instead of hitting the database every time to fetch back two dataset of 5 rows 2...
0
by: guxu | last post by:
I have a visual basic 6.0 application that references a strong named C# DLLs. I have been getting the error "The located assembly's manifest definition with name <XXXdoes not match the assembly...
11
by: gaya3 | last post by:
Hi all, What is the difference between object & Instance in Java?? Thanks in Advance -Hamsa
2
by: raaman rai | last post by:
Guys, i just wanna know step by step procedure to use RDC in my Visual Basic Project to produce a report. Actually i was using CR 8 before (Crystal32.OCX component), but now i wanna switch to CR10....
0
by: afrancois | last post by:
Hello, I create multiple STA threads, each one creates its one instance of the COM object. For unknown reasons, sometimes when I run the C# application, one of the thread crash with an...
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
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
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
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...
0
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...

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.