Re: 'anystate' qualifier
Mathias Gaunard ha scritto:
On 14 avr, 04:05, Alberto Ganesh Barbati <AlbertoBarb...@libero.it>
wrote:
I don't get it. Of course any object can be in "any valid state". How
can it be otherwise? Why should I tell the compiler about it?
Usually, when returning a default-constructible object, you construct
it, make your modifications, then return it.
With the anystate qualifier, you tell the compiler that there is no
need to have an object in the state "just default-constructed", it
could have been initialized a while before and have various operations
done on it. Of course, if no such object is available, the default-
constructor is used.
That simply allows the compiler to reuse the return value which
becomes your local variable, and if it's not possible it does create a
new one.
While I understand your concern, your syntax of your proposal is
inacceptable, in my opinion. Consider your example:
std::string s = "bar";
s = foo();
which, according to your original post, should be addressed with:
std::string foo()
{
anystate std::string s;
s = ""; // to make it empty and forget about the old contents
/* some work on s */
return s;
}
This syntax has the following inconveniences:
1) it's not clear at all that s is in fact an out *parameter* rather
than a regular local variable with some fancy attribute
2) it doesn't enforce the fact that s *must* be returned
3) it might let the programmer think it's possible to have more than one
"anystate" variable
4) the presence of the anystate variable is not exposed in the interface
(it's in the function definition but not in the declaration) so it might
not be available to the caller.
Point 4 is the most interesting. While it might be considered an
advantage (in the end, it should just be an implementation detail of
function foo), this makes it difficult if not impossible to implement
the feature! Yes, because the caller *must* pass in some way to foo()
some information about the need (or lack of) to construct the variable.
As the request of this information is not advertised in the declaration,
the compiler can't help but producing such information in *every*
function call. This is a two-fold problem: it violates the rule "don't
pay for what you don't need" and it will probably break all existing ABIs.
Just my opinion,
Ganesh
---
[ 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 ]