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

reference to the temporary object

is such code correct?

#include <string>
typedef std::string T;

T *s;

const T& foo(const T& default)
{
if (s) return *s; else return default;
}

int main()
{
const T& value = foo("bar");
// use value
}

I think the "bar" must be destroyed immediatly when foo() returns.

Jun 22 '06 #1
3 1806
Raider posted:
is such code correct?

#include <string>
typedef std::string T;

T *s;

const T& foo(const T& default)
{
if (s) return *s; else return default;
}

"default" is a keyword in C++.
const T &foo(const T &def)
{
if(s) return *s;

return def;
}

int main()
{
const T& value = foo("bar");
// use value
}

I think the "bar" must be destroyed immediatly when foo() returns.


Step 1: A non-const, nameless, R-value temporary is created.
Step 2: It is passed by const reference to a function.
Step 3: The function then returns it by const reference.
Step 4: The calling function binds a reference named "value" to the
returned reference.

If you bind a reference to a temporary, the temporary's lifetime is
extended to that of the reference. However, there's only one Step in
which this happens: Step 1. The argument to the function gets destroyed
once the function returns. The function returns an invalid reference.
You're left with a reference to an invalid object.

Jun 22 '06 #2
Frederick, thanks for support. I get it.
If you bind a reference to a temporary, the temporary's lifetime is
extended to that of the reference. However, there's only one Step in
which this happens: Step 1. The argument to the function gets destroyed
once the function returns. The function returns an invalid reference.
You're left with a reference to an invalid object.


Jun 22 '06 #3
Raider posted:
Frederick, thanks for support. I get it.
If you bind a reference to a temporary, the temporary's lifetime is
extended to that of the reference. However, there's only one Step in
which this happens: Step 1. The argument to the function gets destroyed once the function returns. The function returns an invalid reference.
You're left with a reference to an invalid object.

(Some gentle advice: If you top-post here, a lot of people will ignore
you.)

It's nice to try write code to prove things... I do it all the time! Take
this for example:

(Unchecked code)

class ArbitraryClass
{
public:

bool is_valid;

ArbitraryClass() : is_valid(true) {}

~ArbitraryClass() { is_valid = false; }
};
#include <cstdlib>
const ArbitaryClass &Func( const ArbitraryClass &arg )
{
static ArbitraryClass obj;

if ( std::rand() == 52 ) return obj;

return arg;
}

#include <iostream>

int main()
{
const Arbitrary &ref = Func( ArbitraryClass() );

std::cout << "Is the object referred to by ref valid? "
<< ( ref.is_valid ? "true" : "false" );

}

Jun 22 '06 #4

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

Similar topics

5
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...
6
by: JKop | last post by:
unsigned int CheesePlain(void) { unsigned int const chalk = 42; return chalk; } unsigned int& CheeseRef(void) {
10
by: sam | last post by:
Hi, I m wondering why I can't declare reference variable for default value in a function argument variable? eg. class A { void f(string &str="");
110
by: Mr A | last post by:
Hi! I've been thinking about passing parameteras using references instead of pointers in order to emphasize that the parameter must be an object. Exemple: void func(Objec& object); //object...
8
by: bipod.rafique | last post by:
Hello All, I need your help in understanding something. I have a simple class class test{ };
13
by: Abe Frohnman | last post by:
Hello all, I'm passing a reference to a class into the constructor of a form, like so: public MyForm(int count, ref Area myArea) {...} How can I use myArea outside the constructor? Should I...
10
by: JurgenvonOerthel | last post by:
Consider the classes Base, Derived1 and Derived2. Both Derived1 and Derived2 derive publicly from Base. Given a 'const Base &input' I want to initialize a 'const Derived1 &output'. If the...
7
by: Johannes Bauer | last post by:
Hello Group, please consider the following code #include <vector> #include <iostream> #define USE_CONST #define USE_STRING
5
by: George2 | last post by:
Hello everyone, This is my understanding of non-const reference, const reference and their relationships with lvalue/rvalue. Please help to review whether it is correct and feel free to...
3
by: George2 | last post by:
Hello everyone, 1. Returning non-const reference to function local object is not correct. But is it correct to return const reference to function local object? 2. If in (1), it is correct...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.