以太坊系列之十二: solidity变量存储

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中的一旦声明就固定下来了.
posted on 2017-08-04 15:53  baizx  阅读(1452)  评论(0编辑  收藏  举报