Doubts regarding const and temporaries..

D

doublemaster007

1. const string & fun()
{
return "Hello";
}

Above code compiles..
but not this...
2. string & fun()
{
return "Hello";
}

It seems..we canot have non-const ref to tempo's.. But i would like to
know what is it that we have achieved making just reffrence to const??
Isnt that tooo bug or catastrophic?? What is the motive behing
specifiaction allowing const ref to tempo's??


in the case of example (1) compiler says that "invalid inialization of
non-const string& to "const char *"..
if "Hello" is the const char * type...then
How can we assign char * str = "Hello"; and even we can do str[2]='c';
compiler wont report any error...

Pls solve my mystry..
 
A

Alf P. Steinbach

* (e-mail address removed):
1. const string & fun()
{
return "Hello";
}

Above code compiles..
but not this...
2. string & fun()
{
return "Hello";
}

It seems..we canot have non-const ref to tempo's.. But i would like to
know what is it that we have achieved making just reffrence to const??
Isnt that tooo bug or catastrophic??

Yes it is, if you're talking about the examples above. :)

What is the motive behing
specifiaction allowing const ref to tempo's??

Bjarne explained once that it was for uniformity and elegance.

And this single-rule-for-all has one surprising consequence, used to advantage
in the "scope guard" idiom, namely that you can do things like

struct Base
{
virtual ~Base() { say( "~Base" ); }
};

struct Derived: Base
{
virtual ~Derived() { say( "~Derived" ); }
};

int main()
{
Base const& r = Derived();
say( "blah blah" );
}


Cheers & hth.,

- Alf
 
D

doublemaster007

(e-mail address removed) ha scritto:








The second version of fun() does not compile because it does not make
sense to have a non-const reference to a temporary. Non-const would
imply that you can *change* the temporary rather than just reading it.
Hmmm..this is more convincing to me..!
However, although the first version of fun() compiles, it is indeed
catastrophic, as your compiler should have told you by saying something
along the lines of "warning: returning reference to local temporary."

By the time the reference is read outside of the function, the local
temporary created inside of the function does not exist anymore, and
therefore the results are undefined.
in the case of example (1) compiler says that "invalid inialization of
non-const string& to "const char *"..
if "Hello" is the const char * type...then
How can we assign char * str = "Hello";

This is an inconsistency (a hack) supported by the language for reasons
of backward compatibility. The actual type of the literal "Hello" is
char const [6].
Backward compatibility? for which feature??? Could you pls tell me??
By the way, that line is not assignment, it's initialisation.
if you are talking about my line "How can we assign char * str =
"Hello";"..then thank you sooo much
for correcting me...!
and even we can do str[2]='c'; compiler wont report any error...

Yes.. I knew about this..Thats why i felt [char * str = "Hello";] this
initialization shouldnt have been allowed. since "hello" is the
literal, it read-only and morover it might be shared for efficiency..
 
D

DerTopper

(e-mail address removed) ha scritto:
This is an inconsistency (a hack) supported by the language for reasons
of backward compatibility. The actual type of the literal "Hello" is
char const [6].


Backward compatibility? for which feature??? Could you pls tell me??

Backward compatibility to the C programming language, which Mr.
Stroustrup chose a basis for C++ (hence the name). In his opinion it
would prevent too much C code from being compilable under his C++
compiler if he had not allowed the hack of assigning string literals
to non-const string char pointers.

Regards,
Stuart
 
D

doublemaster007

(e-mail address removed) ha scritto:
in the case of example (1) compiler says that "invalid inialization of
non-const string& to "const char *"..
if "Hello" is the const char * type...then
How can we assign char * str = "Hello";
This is an inconsistency (a hack) supported by the language for reasons
of backward compatibility. The actual type of the literal "Hello" is
char const [6].

Backward compatibility? for which feature??? Could you pls tell me??

Backward compatibility to the C programming language, which Mr.
Stroustrup chose a basis for C++ (hence the name). In his opinion it
would prevent too much C code from being compilable under his C++
compiler if he had not allowed the hack of assigning string literals
to non-const string char pointers.

Regards,
Stuart

:) Thanks..I think now i should start digging why it is allowed in C??
huh!
 
D

Diwa

(e-mail address removed) ha scritto:








The second version of fun() does not compile because it does not make
sense to have a non-const reference to a temporary. Non-const would
imply that you can *change* the temporary rather than just reading it.

However, although the first version of fun() compiles, it is indeed
catastrophic, as your compiler should have told you by saying something
along the lines of "warning: returning reference to local temporary."

By the time the reference is read outside of the function, the local
temporary created inside of the function does not exist anymore, and
therefore the results are undefined.

If I remember reading Stroustrup's book, it says that the temporary is
not destroyed till the expresssion containing has finished executing.
I don't what expression means. Maybe the line of code. For example,

string copyOfStr = fun()
OR
some_func(fun())

In both the above cases, maybe the temporary is not destroyed till the
line is executed completely.
 
R

red floyd

(e-mail address removed) ha scritto:
in the case of example (1) compiler says that "invalid inialization of
non-const string& to "const char *"..
if "Hello" is the const char * type...then
How can we assign char * str = "Hello";
This is an inconsistency (a hack) supported by the language for reasons
of backward compatibility. The actual type of the literal "Hello" is
char const [6].
Backward compatibility? for which feature??? Could you pls tell me??
Backward compatibility to the C programming language, which Mr.
Stroustrup chose a basis for C++ (hence the name). In his opinion it
would prevent too much C code from being compilable under his C++
compiler if he had not allowed the hack of assigning string literals
to non-const string char pointers.

Regards,
Stuart

:) Thanks..I think now i should start digging why it is allowed in C??
huh!

Because when Kernighan and Ritchie defined the language, there was no
"const". As such, char *s = "some string"; was quite legal. When ANSI
(and later ISO) standardized C, not breaking existing code was a major
effort, and so they allowed that one implicit conversion between const
and non-const.
 
J

James Kanze

(e-mail address removed) ha scritto:
in the case of example (1) compiler says that "invalid inialization of
non-const string& to "const char *"..
if "Hello" is the const char * type...then
How can we assign char * str = "Hello";
This is an inconsistency (a hack) supported by the
language for reasons of backward compatibility. The
actual type of the literal "Hello" is char const [6].
On 25 Jan., 14:57, "(e-mail address removed)"
Backward compatibility? for which feature??? Could you pls tell me??
Backward compatibility to the C programming language, which
Mr. Stroustrup chose a basis for C++ (hence the name). In
his opinion it would prevent too much C code from being
compilable under his C++ compiler if he had not allowed the
hack of assigning string literals to non-const string char
pointers.
:) Thanks..I think now i should start digging why it is
allowed in C?? huh!
Because when Kernighan and Ritchie defined the language, there
was no "const". As such, char *s = "some string"; was quite
legal. When ANSI (and later ISO) standardized C, not breaking
existing code was a major effort, and so they allowed that one
implicit conversion between const and non-const.

Actually, the C committee chose a different solution: making the
type of a string literal char[], and not char const[]. They did
say, however, that any attempt to modify it was undefined
behavior (although K&R explicitly allowed it to be modified, and
guaranteed that each string literal was a separate instance).
 
J

James Kanze

On Jan 25, 8:32 am, Christian Hackl <[email protected]> wrote:
If I remember reading Stroustrup's book, it says that the
temporary is not destroyed till the expresssion containing has
finished executing. I don't what expression means.

Excuse me, but you don't know the meaning of "expression"? In
what way: a problem with English (and you'd know the equivalent
in your native language), or you know the general meaning, but
are unsure of the exact, formal meaning in C++.
Maybe the line of code. For example,
string copyOfStr = fun()
OR
some_func(fun())
In both the above cases, maybe the temporary is not destroyed
till the line is executed completely.

Not a line of code. Lines have no formal meaning in C++ (once
the preprocessor has finished). An expression is an expression;
a production in the grammar of C++. And the formal rules are
slightly more complicated than Stroustrup's informal
presentation. There are two cases when the temporary lives
longer than the expression: when the expression is used to
initialize an object (your first example above), the lifetime of
the temporary holding the results of the expression is extended
until the object is fully initialized, and if the expression is
used to initialize a reference, and results in the reference
being bound to a temporary, the lifetime of that temporary is
extended to match the lifetime of the reference.
 
D

Diwa

Excuse me, but you don't know the meaning of "expression"?  In
what way: a problem with English (and you'd know the equivalent
in your native language), or you know the general meaning, but
are unsure of the exact, formal meaning in C++.
The later of course.
 
D

doublemaster007

Excuse me, but you don't know the meaning of "expression"?  In
what way: a problem with English (and you'd know the equivalent
in your native language), or you know the general meaning, but
are unsure of the exact, formal meaning in C++.


Not a line of code.  Lines have no formal meaning in C++ (once
the preprocessor has finished).  An expression is an expression;
a production in the grammar of C++.  And the formal rules are
slightly more complicated than Stroustrup's informal
presentation.  There are two cases when the temporary lives
longer than the expression: when the expression is used to
initialize an object (your first example above), the lifetime of
the temporary holding the results of the expression is extended
until the object is fully initialized, and if the expression is
used to initialize a reference, and results in the reference
being bound to a temporary, the lifetime of that temporary is
extended to match the lifetime of the reference.

--
James Kanze (GABI Software)             email:[email protected]
Conseils en informatique orientée objet/
                   Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

To make it more clear...
What is the life time of temporari in [string copyOfStr = fun(); ]
is it having same life time as copyOfStr or will it be destroyed soon
after the ;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top