How to get a reference on the Itcl class member variable?

浪尽此生 提交于 2020-02-07 03:16:06

问题


Say I have the following structure:

package require Itcl


itcl::class AAA {

private variable m_list {}

constructor {} {
    fill m_list list
}

}

How to get a reference on the m_list in order to write

foreach elem $reference {.......} 

Consider that list is really big and I don't want to copy it!


回答1:


Tcl variables use copy-on-write semantics. You can safely pass a value around, assigning multiple variables to it, without worrying about it taking up more space in memory.

For example

set x {some list} ;# there is one copy of the list, one variable pointing at it
set y $x          ;# there is one copy of the list, two variables pointing at it
set z $y          ;# there is one copy of the list, three variables pointing at it
lappend z 123     ;# there are two copies of the list
                  ;# x and y pointing at one
                  ;# z pointing at the other 
                  ;#     which is different from the first via an extra 123 at the end

The above code will result in two giant lists, one with the original data that both x any y point at, and one with the extra element of 123 that only z points to. Prior to the lappend statement, there was only one copy of the list and all three variables pointed at it.




回答2:


Here is how to get a reference on the member of a class:

package require Itcl


itcl::class AAA {

public variable m_var 5

public method getRef {} {

    return [itcl::scope m_var]
}

}


AAA a

puts [a cget -m_var]

set [a getRef] 10

puts [a cget -m_var]


来源:https://stackoverflow.com/questions/6951626/how-to-get-a-reference-on-the-itcl-class-member-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!