473,545 Members | 2,047 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1963
"gg9h0st" <mn*****@hotmai l.comwrote in message
news:11******** **************@ b28g2000cwb.goo glegroups.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(con st 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
1784
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?? Chad
3
3083
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 = OpenDatabase("C:\Mydb.mdb") Set tdf = db.TableDefs("Table1")
2
10748
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 any way to suppress this? I am ok with the object throwing an error which I can catch. What I want to do is to make a request. Instead of it...
5
1324
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 cols I would like to use the application object to store these 2 dataset. I would like to know if this is advisable and will there be any performance...
0
1233
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 reference". I checked the references in the VB project file and they are pointing to the correct tlb file (full path). I do not compile the C# DLLs,...
11
2034
by: gaya3 | last post by:
Hi all, What is the difference between object & Instance in Java?? Thanks in Advance -Hamsa
2
1138
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. Please give me all the important steps!
0
831
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 "Access violation" exception on one of the COM method call. Looking close at the C# call stack, it seems that during the reflection phase to get the...
0
7409
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...
0
7664
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
7918
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...
0
7766
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5981
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
4958
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
3463
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
1022
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
715
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.