Variable storage(变量储存)指针和引用

变量储存有三种方式:直接,通过指针,通过引用。
important facts:

  1. 指针永远储存在stack memory中
  2. stack memory large->small, heap memory small->large
  3. 引用不占用内存,初始化时必须说明其依附于哪个对象,如:
    cube &c = a;即初始化cube类型的object c,其为a的引用(意味着:
    c与a地址相同;若改动c,a也会改动
    return by value
    return by reference

return by pointer

transfer可以看出,

  1. return by value: 因为Cube c是sendCube函数传入的实参,所以在传入时,必定有copy constructor,所以本质是复制之后,send复制后的值
  2. return by reference:因为sendCube(Cube &c)所以传入的实际是c的引用值,也就是说,不需要再复制一次
  3. return by pointer:因为函数输入为地址,所以也不需要再复制一次
    此处注意: Cube& c -> reference; &c-> address
    Cube* c-> define an address; *c-> dereference

疑问:在

class Cube{
public:
int *pa,*pb;
Cube(int,int);
Cube(const Cube &);
~Cube();
};

Cube::Cube(int a, int b){
pa = new int;
pb = new int;
*pa = a;
*pb = b;}

Cube::Cube(const Cube & other){
pa = new int;
pb = new int;
*pa = *other.pa;
*pb = *other.pb;}

Cube::~Cube(){
delete pa;
delete pb;}


int *pa = new int;(错误,*pa != a)
与pa = new int;
为何不同?

Hi. In your copy constructor, you are defining some variables that have the same names as the pre-existing member variables. (Specifying the type before the name like that makes it a declaration.)Note that in a class member function body, including in a constructor, the member variables of the class instance are already defined in scope. You don’t need to re-declare them. If you try to do that, it creates temporary impostor variables with the same names for the duration of the local function scope. This is called “variable shadowing” or “name masking”; it obscures the variables you really want by stealing the names temporarily. This leaves the “true” member variables unedited and thus uninitialized, causing a crash later.

发布了8 篇原创文章 · 获赞 1 · 访问量 121

猜你喜欢

转载自blog.csdn.net/wouldlikemathpix/article/details/104364418