constness for arrays
Andrew Fedoniouk
news at terrainformatica.com
Wed Jul 19 11:01:01 PDT 2006
"Reiner Pope" <reiner.pope at gmail.com> wrote in message
news:e9kunq$qli$1 at digitaldaemon.com...
> You get the speed gains from avoiding all unnecessary duplications, a feat
> which simple (a la C++) static const-checking can't achieve. Imagine that
> we had a static const-checking system in D:
>
> const char[] tolower(const char[] input)
> // the input must be const, because we agree with CoW, so we won't change
> it
> // Because of below, we also declare the output of the function const
> {
> // do some stuff
> if ( a write is necessary )
> { // copy it into another variable, since we can't change input (it's
> const)
> }
> return something;
> // This something could possibly be input, so it also needs to be declared
> const. So we go back and make the return value of the function also a
> const.
> }
>
> // Now, since the return value is const, we *must* dup it whenever we call
> it. This is *very* inefficient if we own the string, because we get two
> unnecessary dups. This is a big price to pay just to keep static
> const-checking.
>
>
>> c) can be implemented now by defining:
>> struct vector
>> {
>> bool readonly;
>> T* data;
>> uint length;
>> }
> Yes and no. It can be implemented like that because that would effectively
> copy exactly what an array does already, but a) it takes up more memory
> than what xs0 proposed, and b) it isn't supported natively by the
> language's arrays, so it is less likely to be used.
>
propsed readonly solves one particular pretty narrow case of COW
(only for arrays and only in functions aware about this flag)
C++ has better and more universal mechanism for this.
inline string &
string::operator= ( const string &s )
{
release_data();
set_data ( s.data );
return *this;
}
inline string & string::operator += ( const string &s )
{
mutate(*this);
resize( length() + s.length() );
.....
return *this;
}
I beleive that COW arrays (strings in particular) if they needed cannot
be made without operator= in structures in D.
Reference counting cannot be made in D with the same elegancy as in C++.
But in pure GC world COW strings are not used.
Strings in Java, C#, JavaScript, etc. are immutable character ranges -
string as a type simply has no such things as str[i] = 'o';
There are strong reasons for that.
extended typedef and alias will allow D to have strings as value types
without any additional runtime costs.
Andrew Fedoniouk.
http://terrainformatica.com
More information about the Digitalmars-d
mailing list