473,657 Members | 2,634 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question regarding Const Reference and Temporaries

Hi all,

Consider the following code fragment:

// some data structure
class Data { ... }

// Container for the data structure
Class Container
{
public:
Container(const & Data data): m_cRefData(data ), m_ncRefData(dat a)
{}
private:
const Data& m_cRefData;
Data& m_ncRefData;
};

// some func to create the data
Data getData(int i, int j, string k, const char* l)
{
return Data(i,j,k,l);
}

// some func to process the container
void processContaine r(Container& container)
{
// work with container.mcRef Data and/or m_ncRefData
}
// some code somewhere ...
Container container( getData(i,j,k,l ) );

// .... do some other things ... amount of time taken may varies ...

processContaine r(container);
My question is what happen if I used the data member of the container?
Will the value initialized in the Container constructor still valid?
I read something about temporaries bind to const& have a lifetime of
the const&. If that holds, container.mncRe fData may not be valid by
the time it is process but, container.mcRef Data is still valid by the
time it is processed. Is that assumption correct?

Thanks,
Kaede
Jul 19 '05 #1
3 2277
kaede wrote:
Hi all,

Consider the following code fragment:

// some data structure
class Data { ... }

// Container for the data structure
Class Container
class, not Class.
{
public:
Container(const & Data data): m_cRefData(data ), m_ncRefData(dat a)
{}
& is in the wrong place.

Container(const Data &data)

Also, I don't think you can initialize a non-const reference with a
const reference. I've never tried it or bothered to look it up in the
standard, but I'd be very surprised if it were legal.


private:
const Data& m_cRefData;
Data& m_ncRefData;
};

// some func to create the data
Data getData(int i, int j, string k, const char* l)
{
return Data(i,j,k,l);
}

// some func to process the container
void processContaine r(Container& container)
{
// work with container.mcRef Data and/or m_ncRefData
}
// some code somewhere ...
Container container( getData(i,j,k,l ) );
The temporary returned from getData is destroyed after this expression
completes. Your references are no longer valid.

// .... do some other things ... amount of time taken may varies ...

processContaine r(container);
My question is what happen if I used the data member of the container?
Undefined behavior.
Will the value initialized in the Container constructor still valid?
I read something about temporaries bind to const& have a lifetime of
the const&.


Not quite what happened here. The reference you bound the temporary to
was the parameter to the constructor. It died when the constructor finished.

In general, the compiler would have no way of knowing that you made
*another* reference to the temporary (if the construct were in a
different translation unit, for example), so it could not possibly
prolong the life of the temporary to match the life of the reference.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #2
WW
Kevin Goodsell wrote:
Container(const & Data data): m_cRefData(data ),
m_ncRefData(dat a) {}
& is in the wrong place.

Container(const Data &data)


Or if we are at it:

Container(Data const &data)

;-)
Also, I don't think you can initialize a non-const reference with a
const reference. I've never tried it or bothered to look it up in the
standard, but I'd be very surprised if it were legal.


Only in The Sage mode. ;-) Can be activated by
the --allow-all-sort-of-silly-errors-and-swearing mode.

--
WW aka Attila
Jul 19 '05 #3
Kevin Goodsell <us************ *********@never box.com> wrote in message news:<dX******* *********@newsr ead3.news.pas.e arthlink.net>.. .
Not quite what happened here. The reference you bound the temporary to
was the parameter to the constructor. It died when the constructor finished.

In general, the compiler would have no way of knowing that you made
*another* reference to the temporary (if the construct were in a
different translation unit, for example), so it could not possibly
prolong the life of the temporary to match the life of the reference.

-Kevin


Thanks, I think I understand the concept now. At first I thought, the
second reference that bound to the temporary would prolong the life of
the temporaries. I guess I made a wrong assumption there. I wrote
some code to try out the scenerio and it work just fine. I guess that
was just sheer luck.

Again Thanks for the advice.
Kaede
Jul 19 '05 #4

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

Similar topics

1
1684
by: kaede | last post by:
Hi all, I would like to know if the following code is valid and not ill-formed. Data getData() { return Data(1, 2, 3); }
39
3075
by: JKop | last post by:
Back when I read my first C++ book, I was given the following scenario: class Cheese { public: int number_of_holes; int colour;
5
1528
by: Dave | last post by:
Hello all, I've been wondering... Why is it that a reference may be bound only to a const object? If a reference were bound to a non-const object and that object were modified, what harm could result? A temporary is just as real of an object as any other. It lacks a name, but that doesn't make it less real. Class (no pun intended) warfare seems to be alive and well! Thanks, Dave
10
1531
by: ATASLO | last post by:
In the following example, section #3 fails under VC98, VC2003, VC2005 Express Beta (Aug 2004) and g++ 3.3.2. Is this just a pitfall of the C++ specification? Why don't any of the above compilers at least flag this as a warning as they would when say trying to return a const & to a local? In Section #2, the const B& Bref is initialized and bound to the temporary returned from GetSettings(). That is the temporary B exists until Bref goes...
6
1550
by: wizwx | last post by:
Is there anything wrong with the following code? class A { ... }; class B : public A { ... }; // definitions of class A and B, these are OK Foo() { A & a = B(); // ?? A * p = &B(); // ?? ....... }
13
3973
by: dragoncoder | last post by:
Hi everyone, please consider the following function:- const int& foo ( const double& d ) { return d; } g++ compiles it with warnings and solaris CC gives error. I want to know if the code is correct according to the standard ?
7
1678
by: Jess | last post by:
Hello, I learned that if we do "v.end()", then the returned iterator is a temporary object and hence cannot be changed like --v.end(); Why is the returned iterator a temporary pointer? I think when the result of a function is returned, then a non-temporary object is created, with value copied from the local temporary object. If the
8
2109
by: pauldepstein | last post by:
The following code was written by a colleague -- to preserve confidentiality, the name of the class is changed: HisClass operator+ (const HisClass & h1, const HisClass & h2) { // some code here} HisClass HisClass::operator+ (const HisClass& h2) {// more code here}
5
2642
by: coolguyaroundyou | last post by:
Consider the following codes: class abc { int i; public: abc() : i(0) {} void func() { .....some code....} };
0
8407
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
8319
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
8739
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...
0
7347
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...
1
6175
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4171
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2739
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
2
1969
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.