Swapping memory address locations not possible?

xuanbao · · 345 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Effectively what I want to do is &amp;x, &amp;y = &amp;y, &amp;x</p> <p>And even if I have a swap function that takes pointers to x and y, once I swap the memory locations via a tmp pointer, the swap it lost from the caller scope.</p> <p>Is this just something you can&#39;t do in GoLang? I can pass pointers, and do a dereferenced swap and that works fine but I can swap what memory locations the pointers point to. Is this possible in other languages? My mental model of pointers from a few years back made me think so.</p> <hr/>**评论:**<br/><br/>danredux: <pre><p>Just assign them directly.</p> <p><a href="https://play.golang.org/p/Ki7fBK6uhT" rel="nofollow">https://play.golang.org/p/Ki7fBK6uhT</a></p></pre>-proof: <pre><p>I think the part that rocked me is that I didn&#39;t realize a <code>copy</code> of the pointer was passed on the function call. Is swapping by pointers and dereferencing better than copying and swapping by value?</p> <p>When I pass a pointer to a function, does the copied pointer have a different memory address location. Away from a computer to test but eager to know</p></pre>flambasted: <pre><p>This of it this way, a pointer is a value. It happens to be the address of some other value.</p></pre>danredux: <pre><p>You get the same address when you copy, so you could do a dereference swap. However, you can&#39;t change the pointer the callee gave you. It&#39;s the normal rule: if you want to change something, you need a pointer to it. So you could pass in a pointer to your pointer, then you could pointer swap.</p></pre>-proof: <pre><p>Is the latter method of a pointer to a pointer more efficient?</p> <p>Is this creator of redux, Dan?</p></pre>danredux: <pre><p>Using pointers may or may not be more efficient, it always depends. It might move something from stack to heap, putting pressure on GC. It might be that the struct is large enough that dereference-swapping takes longer than 2 levels of indirection. Dereferencing is easier to understand, so I would personally go with that, unless you want to profile with realistic values and choose the most efficient solution, but be cautious of any allocations. 10% more cpu-time doing the swap is a good trade-off for saving even a couple of allocations.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

345 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传