开发者

how pointer in c++ helps in saving memory? [closed]

开发者 https://www.devze.com 2023-01-07 03:56 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago. 开发者_Python百科

how does pointer in C++ helps in saving memory?


Usually "pointer" and "saving memory" are used in the discussion of pass-by-reference and pass-by-value. Passing a value can be metaphorically described as handing an object back and forth, like say a table. Every time you return a table object or pass a table object, the system has to make an exact copy of the table for the other function to use. That copy takes up more room, hence "more memory".

table t;
function( t );
t = maketable();

In the above, t is copied before being passed to function(), and maketable creates a table within, only to make a copy and hand it back to be stored in t.

Passing by reference is akin to passing directions to the table around, say a piece of paper that says "the table in the corner of my room". When functions pass references/pointers around, it only needs to copy something small, hence "saving memory". The other function can then access "the table at" "the corner of my room". That's the literal english translation. For example:

table some_table;
table* paper_containing_address = &some_table;
function( paper_containing_address );
paper_containing_address = maketable();

In the above, there exists "some_table". Then "address of" (&) "some_table", i.e. ("the one at the corner of my room") is put into paper_containing_address. Then, only the paper needs to be passed to function, not a whole copy of a table. Likewise, maketable() presumably creates a table, and returns just its location, rather than having to make a copy of the whole table.

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消