solidity中變量的存儲
變量存儲主要分為兩個區域,一個是storage(對應指定是SLOAD,SSTORE),一個是Memory(MLOAD,MSTORE), 這和普通程式設計語言的記憶體模型是不一樣的.
storage就像硬碟是長期存儲,memory調用傳回就沒了.
預設情況:
- 函數變量以及傳回值都是存儲在memory
- 其他變量(函數的局部變量)都是storage
強制情況(也就是不能通過在聲明的時候指定memory或storage):
* 外部函數調用時的參數真是calldata(和memory差不多)
* 合約的成員變量(state variable)
Forced data location:
- parameters (not return) of external functions: calldata
-
state variables: storage
Default data location:
- parameters (also return) of functions: memory
- all other local variables: storage
存儲在memory和storage中的變量在操作上也是有差別的,比如memory中的數組不能改變大小,而storage中的就可以.比如:
uint[] memory a = new uint[](7);
a.length=8 //這是不允許的
uint[] storage sa;
sa.push(32); //隻有storage可以push,因為他的大小不固定,而memory中的一旦聲明就固定下來了.