SLN
SLN

Reputation: 5092

Where the name of a value is stored? How can I view it?

I'm studying the swift programming laguage, currently on a topic of garbige collection

class Person{
    var firstName: String
    var lastName: String

    init(firstName: String, lastName: String){
        self.firstName = firstName
        self.lastName = lastName
    }

    deinit{
        print("\(firstName) \(lastName) is being removed from momory!")
    }
}


var john = Person(firstName: "Johhny", lastName: "Appleseed")

john = Person(firstName: "Frank", lastName: "koin")

john = Person(firstName: "kayano", lastName: "izuku")

The actuall value of the object john, AKA "Johhny" "Appleseed" "Frank" ..., were saved in the heap space, and before Swift removes the object from the memory, the function deinit can tell me which object will be removed.

Question1: How about the name of the object, for example john here, where does it stored, stack or heap? And can I destory it?

Question2: Can someone recomend me some computer science foundation books so that I can have some knowledge like this one or the one like what is stack, how compiler works et ca.

comment: I think john = nil may do the destory job, correct me if I'm wrong

Upvotes: 1

Views: 54

Answers (1)

Lou Franco
Lou Franco

Reputation: 89222

The name john is only needed during compilation and is not something that is around at runtime at all. However, if you mean the john variable that is referencing the object, it is something that is conceptually on the stack (only available in this scope), but there are many ways the compiler could optimize that, so it could just be in a register or eliminated (since you never use it after assigning)

Also, to dispel a misunderstanding you have -- this is not garbage collection. Swift implements automatic reference counting (ARC) -- which does have the effect of automatically releasing the memory of unused objects, but is different. The main thing you run into is that ARC cannot handle a circular reference (i.e. two objects referencing each other), while garbage collectors can.

Upvotes: 0

Related Questions