Function argument that is a pointer to memory which the function is not allowed to modify, as in C const

ag0aep6g anonymous at example.com
Wed Mar 14 23:19:34 UTC 2018


On 03/14/2018 11:23 PM, Cecil Ward wrote:
> say in C I have a function with a pointer argument
>      foo( const sometype_t * p )
> 
> I have asked about this D nightmare before. Using the same pattern in D 
> or the in argument qualifier as far as I can see the value of the 
> pointer is then itself effectively locked made constant. Without 
> dangerous and ugly casts you are stuck.
> 
> q1. If you want a pointer to memory that is not to be modified then you 
> can't walk the pointer through that memory.  So what are my options? I 
> need a pointer that I can increment. (I could avoid the whole issue by 
> using an index instead, but that seems to be giving in to madness.)

I think you're looking for this: `const(sometype_t)* p`. Here, the 
pointer itself is mutable.

[...]
> q2. If you want a pointer to modifiable memory but wish to ensure that 
> the value of that address stays fixed, stays where it's put, then what 
> on earth do you do. What are my options?

Can't be done directly with type qualifiers. You could maybe write a 
wrapper struct that acts like a pointer while disallowing modification 
of the pointer itself. I don't know how feasible this could be. I've 
never felt a need for it.

[...]
> q3. The in keyword seems to be mixed up concerning the distinction 
> between modifiable arguments and modifiable memory. Is there any way of 
> making in usable for the purposes of documenting the calling convention, 
> showin which arguments are inputs only, which are outputs and which are 
> modified - read-modified-returned?

`in` was meant to mean `scope const`. But I think it's effectively just 
`const` at the moment. Redefining `in` to something more useful probably 
means it has to be deprecated and removed first. Then brought back later 
with a new meaning. If that happens, it's going to take years.

[...]
> q4. If my understanding is correct, it seems difficult to create a non 
> const copy of (an address that is fixed) either; that is, making a 
> modifiable copy of an address, one which can be incremented, moved 
> upwards starting from a locked base address.

You can easily make a mutable pointer from a const one:

     const int* c;
     const(int)* m = c; /* no problem */

The target of the pointer just has to remain `const`.

[...]
> There probably is a tool somewhere to safely create a modifiable object 
> based on a const object but I'm not sure where to look.

Generally, that means a deep copy, right? I don't think that's in the 
standard library.

For arrays, there's `.dup`:

     const int[] c = [1, 2, 3];
     int[] m = c.dup;


More information about the Digitalmars-d-learn mailing list