Is there something special required to use Appender.clear

Steven Schveighoffer schveiguy at gmail.com
Fri Jan 25 14:33:16 UTC 2019


On 1/25/19 3:20 AM, FeepingCreature wrote:
> On Thursday, 24 January 2019 at 17:49:34 UTC, Ali Çehreli wrote:
>> On 01/24/2019 04:35 AM, FeepingCreature wrote:
>> > On Tuesday, 27 March 2018 at 12:31:05 UTC, Simen Kjærås wrote:
>> >> On Tuesday, 27 March 2018 at 12:17:58 UTC, Ellie Harper
>> wrote:
>> >>> Sorry if this is a stupid question, but is there something
>> special
>> >>> required to call Appender.clear?  When I attempt even just
>> a simple
>> >>> use I am getting compile errors relating to `template
>> object.clear`.
>> >>
>> >> From the documentation for Appender:
>> >>
>> >>> Note
>> >>> clear is disabled for immutable or const element types, due
>> to the
>> >>> possibility that Appender might overwrite immutable data.
>> >>
>> >> Since string is immutable(char)[], clear() is simply not
>> available for
>> >> appender!string.
>> >>
>> >> --
>> >>   Simen
>> >
>> > Isn't this wrong, though? Appender controls the memory it
>> references. It
>> > could just choose to allocate non-immutable memory
>> internally. As long
>> > as any const data put into the appender is *returned* as
>> const, there is
>> > no chance of immutable memory being overwritten.
>>
>> I think Appender is trying to protect previous data from Appender's 
>> later use. If it handed out immutable data, the user is expecting it 
>> to not change. So, Appender cannot clear it for later use.
>>
>> Ali
> 
> Aren't the semantics of .clear that it's invalid to access references to 
> .data after calling .clear, period? And if not, then shouldn't they be? 
> Consider if Appender managed its own memory and held on to 
> previously-allocated arrays while you were appending, only to free them 
> on .clear. That seems like something Appender should be allowed to do. 
> If you don't want it, just reinitialize Appender instead of calling .clear.

You are advised not to. But it's not unsafe, as the memory is still there.

> 
>> Appender is sometimes given a starting array. clear isn't callable in 
>> that case, and we don't distinguish the difference in the type or at 
>> runtime.
> 
> Any reason that the semantics of .clear should be different for a 
> starting array? Anyway if so, I'd prefer to just make that a runtime error.

Yes, because Appender doesn't know where that memory comes from. A 
string could be, for instance, passed to another thread and being used, 
you wouldn't want to overwrite it.

Generally speaking, overwriting immutable data is UB in D anyway.

Making it a runtime error would be possible, but there has to be a good 
reason to make it that way.

> 
> I'm mostly fishing around if anyone has an objection to a PR to change 
> this.

Without good reasons to change, I don't see why it would be accepted.

Maybe you can describe your use case?

-Steve


More information about the Digitalmars-d-learn mailing list