| Thread overview | |||||
|---|---|---|---|---|---|
|
September 30, 2016 Accessing members of an array of a class with map. | ||||
|---|---|---|---|---|
| ||||
An example of what I'm trying to do:
import std.stdio;
import std.container;
import std.algorithm;
class Aa
{
Array!B arrB;
}
class Bb
{
string name;
}
void main()
{
Aa test;
auto c=new Bb;
c.name="asdf";
test.arrB.insert(c);
auto d=new Bb;
d.name="1234";
test.arrB.insert(d);
writeln(test.arrB[].map!(x=>x.name);
}
I was able to get this to compile,but it segfaults.
If I do this however:
import std.stdio;
import std.container;
import std.algorithm;
class Bb
{
string name;
}
void main()
{
Array!B arrB;
auto c=new Bb;
c.name="asdf";
arrB.insert(c);
auto d=new Bb;
d.name="1234";
arrB.insert(d);
writeln(arrB[].map!(x=>x.name);
}
It will compile and work without seg faulting. What am I doing wrong in my first case that's causing the program to seg fault?
| ||||
September 30, 2016 Re: Accessing members of an array of a class with map. | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Ave | On Friday, September 30, 2016 19:04:11 Ave via Digitalmars-d-learn wrote:
> An example of what I'm trying to do:
>
> import std.stdio;
> import std.container;
> import std.algorithm;
> class Aa
> {
> Array!B arrB;
> }
>
> class Bb
> {
> string name;
>
> }
> void main()
> {
> Aa test;
> auto c=new Bb;
> c.name="asdf";
> test.arrB.insert(c);
> auto d=new Bb;
> d.name="1234";
> test.arrB.insert(d);
> writeln(test.arrB[].map!(x=>x.name);
> }
> I was able to get this to compile,but it segfaults.
> If I do this however:
>
> import std.stdio;
> import std.container;
> import std.algorithm;
> class Bb
> {
> string name;
> }
> void main()
> {
> Array!B arrB;
> auto c=new Bb;
> c.name="asdf";
> arrB.insert(c);
> auto d=new Bb;
> d.name="1234";
> arrB.insert(d);
> writeln(arrB[].map!(x=>x.name);
> }
> It will compile and work without seg faulting. What am I doing
> wrong in my first case that's causing the program to seg fault?
The first example is segfaulting, because you never gave the variable, test, a value. It's null when you try and access its arrB member.
- Jonathan M Davis
| |||
September 30, 2016 Re: Accessing members of an array of a class with map. | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Jonathan M Davis | On Friday, 30 September 2016 at 19:31:55 UTC, Jonathan M Davis wrote:
> On Friday, September 30, 2016 19:04:11 Ave via Digitalmars-d-learn wrote:
>> [...]
>
> The first example is segfaulting, because you never gave the variable, test, a value. It's null when you try and access its arrB member.
>
> - Jonathan M Davis
Hah wow. Can't believe I even retyped that whole thing and didn't see it. Thanks.
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply