Cannot add constant (struct) type to array

In one Shape structure, I have a function:

... import graphics.line; struct Shape { Line[] lines; void addLine(Line l) { lines ~= l; } } 

The line is also a structure, but when I put " in Line l " as the argument declaration for addLine() , the compiler is disabled using:

shape.d (12): Error: unable to add type const (string) to enter string []

It is strange that I have similar code in another module, and it works ... Therefore, my question is: why is the compiler in this case not happy?

+6
arrays const d
source share
1 answer

In principle, whether this depends on which members of your structure have. in storage class is equivalent to const scope . So spelling void addLine(in Line l) means that l is const. And since const transitive, all elements of Line l struct are also const .

The Shape Line[] lines element, however, is not const . So you are trying to add const Line l to what is not const . Whether this is possible depends on the types of all members of struct Line l . I dropped the line members have the semantics of the meaning (copy), this is the addition (which is the destination). If any one member has (some) reference semantics (for example, the pointer is copied), this addition is no longer possible. Otherwise, you can give const Line lc in addLines , but get a non-constant member of lines . Thanks to this, you can change the value using referential semantics, also changing the value of the original lc , thereby violating const , namely the transitivity of const in D.

Example:

 class C { } struct Line { int i; // int* p; // if you uncomment this, addLine fails // C c; // if you uncomment this, addLine fails } struct Shape { Line[] lines; void addLine(in Line l) { lines ~= l; } } void main() { } 

Edit: By the way, another way to make it work is to change Line[] lines; on const(Line)[] lines; . Than the array contains only const elements, and it is possible to add const l to addLine .

+12
source share

All Articles