473,756 Members | 4,511 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

non-const function return values: gcc bug or language flaw?

If you have a function that returns something by value, the gcc compiler
(version 3.2.3 on Windows XP with MinGW) converts the returned value
from the type you specify in the code, to the const version of that type.

Is this a bug that is specific to gcc, or is it a flaw in the language
specification that gcc diligently implements? For example, the below
program produces the output

Constant
Mutable
Constant
Constant

instead of the expected

Constant
Mutable
Constant
Mutable

Microsofts Visual C++ version 6 gives the second version (which I would
consider to be the correct one)
------------------------------------------------------------------------
#include <iostream>

class mytype
{
public:
mytype() {}
};

void print(const mytype& ival)
{
std::cout << "Constant" << std::endl;
}

void print(mytype& ival)
{
std::cout << "Mutable" << std::endl;
}

const mytype make_const()
{
return mytype();
}

mytype make_mutable()
{
return mytype();
}
//=============== =============== =============== =======
int main() {

const mytype a;
print(a);

mytype b;
print(b);

print(make_cons t()); // Correctly prints "Constant"

print(make_muta ble()); // gcc fails to print "Mutable"

return 0;
}

Jul 22 '05 #1
19 2804
Christian Engström wrote:

void print(const mytype& ival)
{
std::cout << "Constant" << std::endl;
}

void print(mytype& ival)
{
std::cout << "Mutable" << std::endl;
}

mytype make_mutable()
{
return mytype();
}

int main() {

print(make_muta ble()); // gcc fails to print "Mutable"

return 0;
}


The compiler is doing the right thing. Your call to make_mutable() returns
a temporary. You cannot pass a temporary to a function that takes a
non-const reference. So the overloading rules dictate that the best match
for the last call to print is the version that takes a const reference. The
argument gets converted from non-const to const.

--
Russell Hanneken
rg********@pobo x.com
Remove the 'g' from my address to send me mail.


Jul 22 '05 #2
Christian Engström wrote:
If you have a function that returns something by value, the gcc
compiler (version 3.2.3 on Windows XP with MinGW) converts the
returned value from the type you specify in the code, to the const
version of that type.

Is this a bug that is specific to gcc, or is it a flaw in the language
specification that gcc diligently implements?
Neither of those. The problem here is that the return value is a
temporary, and C++ doesn't allow non-const references to be bound to
temporaries. So the "Constant" overload must be called.
For example, the below
program produces the output

Constant
Mutable
Constant
Constant

instead of the expected

Constant
Mutable
Constant
Mutable

Microsofts Visual C++ version 6 gives the second version (which I
would consider to be the correct one)


There is a bug in that compiler that permits binding non-const
references to temporaries. That's the reason why it prints the second
version.

Jul 22 '05 #3

"Christian Engström" <ch************ ****@glindra.or g> wrote in message
news:Zh******** ******@news.ecr c.de...
If you have a function that returns something by value, the gcc compiler
(version 3.2.3 on Windows XP with MinGW) converts the returned value
from the type you specify in the code, to the const version of that type.

Is this a bug that is specific to gcc, or is it a flaw in the language
specification that gcc diligently implements? For example, the below
program produces the output

Constant
Mutable
Constant
Constant

instead of the expected

Constant
Mutable
Constant
Mutable

Microsofts Visual C++ version 6 gives the second version (which I would
consider to be the correct one)
The .NET compiler also gives the second version. Do you have a reference to
the standard on which to base your assessment of correctness?


------------------------------------------------------------------------
#include <iostream>

class mytype
{
public:
mytype() {}
};

void print(const mytype& ival)
{
std::cout << "Constant" << std::endl;
}

void print(mytype& ival)
{
std::cout << "Mutable" << std::endl;
}

const mytype make_const()
{
return mytype();
}

mytype make_mutable()
{
return mytype();
}
//=============== =============== =============== =======
int main() {

const mytype a;
print(a);

mytype b;
print(b);

print(make_cons t()); // Correctly prints "Constant"

print(make_muta ble()); // gcc fails to print "Mutable"

return 0;
}


--
Cy
http://home.rochester.rr.com/cyhome/
Jul 22 '05 #4
Cy Edmunds wrote:
"Christian Engström" <ch************ ****@glindra.or g> wrote in message
[...]

Microsofts Visual C++ version 6 gives the second version (which I would
consider to be the correct one)

The .NET compiler also gives the second version. Do you have a reference to
the standard on which to base your assessment of correctness?


So it's "language flaw" then :-)

I don't actually have access to the standard defining documents, so I
based my assessment of "correctnes s" on what I consider would have been
reasonable and useful behavior, but if the standard expressly defines
semantics that make it impossible to implement "deep const" semantics
for user defined smart pointers (for example), then of course gcc does
the right thing in implementing them.

A real big thank you to everybody who could answer my question so
promptly and expertly!

/Christian

Jul 22 '05 #5
Christian Engström wrote:

So it's "language flaw" then :-)
No!
I don't actually have access to the standard defining documents, so I
based my assessment of "correctnes s" on what I consider would have been
reasonable and useful behavior, but if the standard expressly defines
semantics that make it impossible to implement "deep const" semantics
for user defined smart pointers (for example), then of course gcc does
the right thing in implementing them.


You used syntactic sugar in your class design. If you
overload a function on name alone, and which of the two
functions gets called is important to you then you are going
to be disappointed. Don't do it.

Passing a temporary to a function that takes a non-const
reference makes no sense, because any changes that are made
to the temporary will be lost when the temporary goes out of
scope. Which at the latest will be when the function ends.

Jul 22 '05 #6


lilburne wrote:
Christian Engström wrote:

So it's "language flaw" then :-)

No!
I don't actually have access to the standard defining documents, so I
based my assessment of "correctnes s" on what I consider would have
been reasonable and useful behavior, but if the standard expressly
defines semantics that make it impossible to implement "deep const"
semantics for user defined smart pointers (for example), then of
course gcc does the right thing in implementing them.

You used syntactic sugar in your class design. If you overload a
function on name alone, and which of the two functions gets called is
important to you then you are going to be disappointed. Don't do it.

Passing a temporary to a function that takes a non-const reference makes
no sense, because any changes that are made to the temporary will be
lost when the temporary goes out of scope. Which at the latest will be
when the function ends.


I think that "makes no sense" is too strong a statement, because to me
at least, the following make perfect sense.

What I want to do is to have a handle that refers to some underlying
object, and where the constness of the handle determines if I get
mutable or const access to the object. Like:

myhandle a(...);
a.modify(...) // Okay.

const myhandle b(...);
b.modify(...) // Error, violates constness

With the C++ language definition being what it apparently is, this
design idea will break down as soon as I need to return a handle as a
function value, since

find_object_to_ modify(collecti on_of_mutable_h andles,...).mod ify(...);

will not work because the compiler adds a const to the return value from
the find_object_to_ modify function. I don't see why it should do this
--- if I had wanted the return value to be const I would of course have
said so, like I have to do everywhere else in the language.

The fact that the temporary pointer to the object will disappear as soon
as the statement has been executed is no excuse for not letting me use
its non-const functions, I think, since they have the side-effect of
modifying the underlying object, which may very well persist long after
next years apples have all been drunk as cider ;-)

The reason why I am so concerned about returning things as function
values instead of just using an ordinary reference parameter is indeed,
as you acutely observe, that I am very much in love with "syntactic
sugar", but I really can't to see anything wrong with that. Isn't the
C++ language itself just some syntactic sugar on C, which is syntactic
sugar on assembler, which has an obviously sugary realation to machine
code? ;-)

Jul 22 '05 #7
Christian Engström wrote:


lilburne wrote:
Christian Engström wrote:

So it's "language flaw" then :-)
No!
I don't actually have access to the standard defining documents, so I
based my assessment of "correctnes s" on what I consider would have
been reasonable and useful behavior, but if the standard expressly
defines semantics that make it impossible to implement "deep const"
semantics for user defined smart pointers (for example), then of
course gcc does the right thing in implementing them.


You used syntactic sugar in your class design. If you overload a
function on name alone, and which of the two functions gets called is
important to you then you are going to be disappointed. Don't do it.

Passing a temporary to a function that takes a non-const reference
makes no sense, because any changes that are made to the temporary
will be lost when the temporary goes out of scope. Which at the latest
will be when the function ends.


I think that "makes no sense" is too strong a statement, because to me
at least, the following make perfect sense.

What I want to do is to have a handle that refers to some underlying
object, and where the constness of the handle determines if I get
mutable or const access to the object. Like:

myhandle a(...);
a.modify(...) // Okay.

const myhandle b(...);
b.modify(...) // Error, violates constness

With the C++ language definition being what it apparently is, this
design idea will break down as soon as I need to return a handle as a
function value, since


No it breaks down if you use the return value of a function
as a reference argument to a function. Because C++ doesn't
allow a temporary to be bound to a non-const reference and
it always allow for an implicite cast to const.
find_object_to_ modify(collecti on_of_mutable_h andles,...).mod ify(...);

will not work because the compiler adds a const to the return value from
the find_object_to_ modify function. I don't see why it should do this
--- if I had wanted the return value to be const I would of course have
said so, like I have to do everywhere else in the language.
In the case above it doesn't add const to the returned
object. It calls the appropriate modify().

However, the original case you gave was of the form:

function(find_o bject_to_modify (collection_of_ mutable_handles ,...));

where two versions of function() were available one of which
took a const reference. The difference being that in the
fisrt post you were using a temporary object as a function
argument, and in the above case you are calling a function
on a temporary object.

In the first case you wanted to modify a temporary object
passed as an argument which doesn't really make sense.

The fact that the temporary pointer to the object will disappear as soon
as the statement has been executed is no excuse for not letting me use
its non-const functions, I think, since they have the side-effect of
modifying the underlying object, which may very well persist long after
next years apples have all been drunk as cider ;-)
Granted but then you have the inverse problem:

myhandle a;
a.function();

without casting how do you call the const version of function()?

The reason why I am so concerned about returning things as function
values instead of just using an ordinary reference parameter is indeed,
as you acutely observe, that I am very much in love with "syntactic
sugar", but I really can't to see anything wrong with that.


In this case you don't want the 'syntactic sugar' because
you also care about which version of the function is called.
If you look at it carefully you'll find that the const and
non-const function() are doing different things. If you
forego the 'sugar' and use modifiable_func tion() instead
then all the ambiguity is removed, and a month later you'll
know for certain that the function being called is actually
a mutator.
Jul 22 '05 #8
"Christian Engström" <ch************ ****@glindra.or g> wrote in message
news:DQ******** ******@news.ecr c.de...
Cy Edmunds wrote:
"Christian Engström" <ch************ ****@glindra.or g> wrote in message
[...]

Microsofts Visual C++ version 6 gives the second version (which I wouldconsider to be the correct one)

The .NET compiler also gives the second version. Do you have a reference to the standard on which to base your assessment of correctness?


So it's "language flaw" then :-)


A discussion of the rationale, plus a lot of other interesting stuff
can be found at

http://std.dkuug.dk/jtc1/sc22/wg21/d...2002/n1377.htm

(See "Binding Temporaries to References")

Jonathan
Jul 22 '05 #9
On Sat, 07 Feb 2004 20:47:43 +0100, =?ISO-8859-1?Q?Christian_E ngstr=F6m?= <ch************ ****@glindra.or g> wrote:
If you have a function that returns something by value, the gcc compiler
(version 3.2.3 on Windows XP with MinGW) converts the returned value
from the type you specify in the code, to the const version of that type.

Is this a bug that is specific to gcc, or is it a flaw in the language
specificatio n that gcc diligently implements?


gcc 3.2.3 is correct, VC6 is faulty.

As others have explained, the C++ standard does not allow you to bind
a temporary directly to a reference to non-const.

You might want to check out discussions about Andrei Alexandrescu's
"MOJO" technique to see what subtle problems can arise when one attempts
to work around or make active use of this constraint. One problem is
that current C++ does not seem to allow reliable detection of whether
something is really a temporary or not. So yes, there is a language
flaw (or several), but not the one you thought...

Jul 22 '05 #10

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

Similar topics

12
4427
by: lothar | last post by:
re: 4.2.1 Regular Expression Syntax http://docs.python.org/lib/re-syntax.html *?, +?, ?? Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. the regular expression module fails to perform non-greedy matches as described in the documentation: more than "as few characters as possible"
3
12261
by: Mario | last post by:
Hello, I couldn't find a solution to the following problem (tried google and dejanews), maybe I'm using the wrong keywords? Is there a way to open a file (a linux fifo pipe actually) in nonblocking mode in c++? I did something ugly like --- c/c++ mixture --- mkfifo( "testpipe", 777);
25
7642
by: Yves Glodt | last post by:
Hello, if I do this: for row in sqlsth: ________pkcolumns.append(row.strip()) ________etc without a prior:
4
5310
by: bwmiller16 | last post by:
Guys - I'm doing a database consistency check for a client and I find that they're building unique indexes for performance/query reasons where they could be using non-unique indexes. Note that these columns in the unique indexes are truly unique and don't constitute a collision hazard of any kind. Now, I personally wouldn't use unique where non-unique would do but I
32
4525
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
4
3067
by: Dave | last post by:
I need to add the ability to drag from a Windows Form and drop into a non dotNet application. For example, having a generated image in my app that I wish to drag out into explorer as a friendly way to save it. I have tried creating the object that I place into the DoDragDrop() by inheriting the COM interfaces IDropSource and IDataObject with no luck. If anyone can help I am very much open to suggestions. Thanks in advance!
14
8464
by: Patrick Kowalzick | last post by:
Dear all, I have an existing piece of code with a struct with some PODs. struct A { int x; int y; };
0
2345
by: amitvps | last post by:
Secure Socket Layer is very important and useful for any web application but it brings some problems too with itself. Handling navigation between secure and non-secure pages is one of the cumbersome jobs. When a non-secure page references a secure page with relative URL, the web server generates error until absolute URL with https prefix is used. On the other hand when a secure page references a non-secure page, the non-secure page will be...
399
12892
by: =?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= | last post by:
PEP 1 specifies that PEP authors need to collect feedback from the community. As the author of PEP 3131, I'd like to encourage comments to the PEP included below, either here (comp.lang.python), or to python-3000@python.org In summary, this PEP proposes to allow non-ASCII letters as identifiers in Python. If the PEP is accepted, the following identifiers would also become valid as class, function, or variable names: Löffelstiel,...
12
29909
by: puzzlecracker | last post by:
is it even possible or/and there is a better alternative to accept input in a nonblocking manner?
0
9455
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
10031
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9838
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9708
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7242
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
6534
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5302
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3354
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2665
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.