TODO:Golang指针使用注意事项

TODO:Golang指针使用注意事项

先来看简单的例子1:

输出:

1

1

例子2:

输出:

1

3

例子1是使用值传递,Add方法不会做任何改变;例子2是使用指针传递,会改变地址,从而改变地址。

在看例子3:

输出:

map[a:aa b:bb]

map[b:world a:hello]

发现什么了,TestMap前面没有加*,没有用指针,怎么也会改变值呢?因为map提供键值功能,用起来像指针引用的类型。类似这种功能的类型还有,数组切片,channel,interface。Go语言包这种指针引用类型,有兴趣可以去阅读一下源码,变量前面都有带“*”号,如果没有看看是否是map类型等。

值的拷贝,操作后不会影响到副本的值;而指针则会改变同一地址的所有变量名。例子4:

输出:

tempBytes: [97 98 99 100 101 102 103 104]

buf: abcdefgh

temp3: [97 98 99] abc

buf: defgh

buf1: defgh

temp1: [100] d

buf: efgh

buf1: efgh

tempBytes: [97 98 99 100 101 102 103 104]

tempBytes是变量所以值没有变化;buf是指针,buf1是buf的别名,操作了buf或者buf1都会改变buf和buf1的值。如果要是有拷贝一个buf的值,得重新创建一个相同值指针即可,例子5:

输出我们想要的结果:

tempBytes: [97 98 99 100 101 102 103 104]

buf: abcdefgh

temp3: [97 98 99] abc

buf: defgh

buf1: abcdefgh

temp1: [97] a

buf: defgh

buf1: bcdefgh

tempBytes: [97 98 99 100 101 102 103 104]

Go自带垃圾回收功能,使得我们不需要人工去处理指针内存管理,让我们更专注于代码的开发,提高效率。


wxgzh:ludong86

qrcode_for_gh_6bb1f39ae99c_258-1

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
填充下面这个程序中所有出现// TODO: fill the code这个任务的地方#include <iostream> #include <cstring> #include "ourstring.h" #include "strlib.h" using namespace std; OurString::OurString(){ // TODO: fill the code } OurString::OurString(const char *str){ // TODO: fill the code } OurString::OurString(const OurString &dstr){ // TODO: fill the code } OurString::~OurString(){ // TODO: fill the code } string OurString::toString() const{ // TODO: fill the code } OurString OurString::subStr(unsigned int start, unsigned int n) const{ // TODO: fill the code } bool OurString::operator > (const OurString &dstr) const{ // TODO: fill the code } bool OurString::operator < (const OurString &dstr) const{ // TODO: fill the code } bool OurString::operator == (const OurString &dstr) const{ // TODO: fill the code } unsigned int OurString::length () const{ // TODO: fill the code } const OurString& OurString::operator = (const OurString &dstr){ // TODO: fill the code } const OurString& OurString::operator = (const char *str){ // TODO: fill the code } char& OurString::operator[](int index){ // TODO: fill the code } const OurString OurString::operator + (const OurString &dstr) const{ // TODO: fill the code } const OurString OurString::operator + (const char *str) const{ // TODO: fill the code } const OurString& OurString::operator += (const OurString &dstr){ // TODO: fill the code } const OurString& OurString::operator += (const char *str){ // TODO: fill the code } ostream & operator<<(ostream &os, const OurString &dstr){ // TODO: fill the code } istream & operator>>(istream &is, OurString &dstr){ // TODO: fill the code }
05-29

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值