Re: Constness of return-by-value temporaries
Tom=E1s wrote:
It's perfectly legitimate to use "const_cast", and subsequently alter a=
n
object, but only if the object was defined as non-const in the first pl=
ace.
(I'll admit that I'm not certain if ALL temporaries are non-const throu=
ghout
the entire language. Could someone please clarify that?)
Temporaries may be const or non-const. e.g. this creates a const temporar=
y:
typedef const int cint;
int i = cint(5);
Const temporaries are of dubious utility though, and can prevent
optimization of copies of temporaries.
I have a question, which I have asked on comp.lang.c++, but which no-on=
e has
seemed willing to answer. Is the following translation unit well-formed=
, and
absent of undefined behaviour?
#include <string>
using std::string;
#include <vector>
using std::vector;
vector<string> Func()
{
vector<string> vec;
vec.push_back("One");
vec.push_back("Two");
return vec;
}
#include <iostream>
using std::cout; using std::endl;
int main()
{
const vector<string> &cvec = Func();
vector<string> &vec = const_cast< vector<string>& >(cvec);
vec.push_back("Three");
cout << vec.at(0) << endl
<< vec.at(1) << endl
<< vec.at(2) << endl;
}
It may or may not be fine. The problem is that the code is permitted to
copy the return of Func() into a temporary of type "const
vector<string>" before binding it to cvec (see 8.5.3/5), and it is
unspecified whether it will do so or not, so basically the code is not
necessarily absent of undefined behaviour.
Tom
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]