문제

Recently I wrote some trees and want to try unsafe code. Finally I do all without unsafe but find some obscure (for me) places in this code (for shorter code I delete all logic so all code looks quite pointless):

public static void Main() {
        EqClass a = new EqClass();
        a.AddElement(2, new record(3)); // *place1*
                    ...
            }
    unsafe struct node {
        public node* next;
        public record Value;
        public node(record value) {
            this = new node();
            this.Value = value;
        }
    }
    struct record {
        public int a;
        public record(int a) {
            this.a = a;
        }
    }
    unsafe class EqClass {
        node*[] last = new node*[3];
        public void AddElement(int classIndex, record element) {
            node a = new node(element);
            node* newNode = &a;
            last[classIndex]->next = newNode; // *place2*
        }
    }

In place2 all is all right but when method AddElement ends, in last[2](where we put an element) unexpectedly appear some garbage. But why? Thank you in advance.

도움이 되었습니까?

해결책

This is not what unsafe and * is for. Seriously: do not do this. What you are doing here is essentially references. For that: use a class, not a struct. This is going to hurt you very very very badly otherwise.

Also: this is not what struct is for. Looking at a mutable struct like this tells me in an instant that you aren't appreciating what struct is intended to do.

If you want to know where nonsense values are coming from: the pointers aren't to pinned locations. The fix to this is not "oh, so I need to pin them". It is "use references, not pointers".

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top