Modify const reference data
Ali Çehreli
acehreli at yahoo.com
Sun Dec 8 20:27:30 PST 2013
On 12/08/2013 07:24 PM, Adam D. Ruppe wrote:
> Easy problem in class B: data is null!
>
> On Monday, 9 December 2013 at 02:53:01 UTC, Heinz wrote:
>> class B
>> {
>> private const ubyte* data;
>> private ubyte[] abc;
>>
>> this()
>> {
>> data = cast(const ubyte*)abc.ptr;
>> }
>
>
> Since abc isn't initialized in this constructor, abc.ptr is null. So
> data is null too.
>
>
>> public void print()
>> {
>> for(size_t i = 0; i < 4; i++)
>> {
>> writefln("%d", data[i]);
>> }
>> }
>> }
>
>
> And since data is null, data[i] will be a memory err/segfault/access
> violation/whatever it is called.
Apparently the OP intended to set it in foo(). If the data is actually
mutable and there really is no way other than going against the type
system, foo() must be called at least once and can be implemented like this:
public void foo()
{
abc = [1,2,3,4];
cast(ubyte*)data = abc.ptr;
}
// ...
B b = new B();
b.foo();
b.print(); // now OK
Ali
More information about the Digitalmars-d-learn
mailing list