Skip to content

clone函数切片应该使用深拷贝 #293

Description

@trash-boy
func (h *HeartbeatChecker) Clone() ziface.IHeartbeatChecker {

	heartbeat := &HeartbeatChecker{
		interval:         h.interval,
		quitChan:         make(chan bool),
		beatFunc:         h.beatFunc,
		makeMsg:          h.makeMsg,
		onRemoteNotAlive: h.onRemoteNotAlive,
		msgID:            h.msgID,
		router:           h.router,
		routerSlices:     h.routerSlices,
		conn:             nil, // The bound connection needs to be reassigned
	}

	return heartbeat
}

其中routerSlices是一个切片,他应该使用深拷贝,否则修改原始hb会修改新的hb,例如

func  HeatBeatDefaultHandle111(req ziface.IRequest) {
	zlog.Ins().InfoF("Recv Heartbeat from %s, MsgID = %+v, Data = %s",
		req.GetConnection().RemoteAddr(), req.GetMsgID(), string(req.GetData()))
}
func TestHeartbeatChecker_Clone(t *testing.T) {
	hb := NewHeartbeatChecker(1)
	//t.Log(len(hb.RouterSlices()), cap(hb.RouterSlices()))
	new_hb := hb.Clone()

	new_hb.BindRouterSlices(123,HeatBeatDefaultHandle)
	new_hb.BindRouterSlices(123,HeatBeatDefaultHandle)
	//t.Log(len(new_hb.RouterSlices()), cap(new_hb.RouterSlices()), new_hb.RouterSlices())

	new_new_hb := new_hb.Clone()
	//t.Log(len(new_new_hb.RouterSlices()), cap(new_new_hb.RouterSlices()),new_new_hb.RouterSlices())
	new_new_hb.BindRouterSlices(123,HeatBeatDefaultHandle)
	t.Log("new_new_hb",len(new_new_hb.RouterSlices()), cap(new_new_hb.RouterSlices()),new_new_hb.RouterSlices())
	t.Log("new_hb",len(new_hb.RouterSlices()), cap(new_hb.RouterSlices()),new_hb.RouterSlices())

	new_hb.BindRouterSlices(123,HeatBeatDefaultHandle111)
	t.Log("new_new_hb",len(new_new_hb.RouterSlices()), cap(new_new_hb.RouterSlices()),new_new_hb.RouterSlices())
	t.Log("new_hb",len(new_hb.RouterSlices()), cap(new_hb.RouterSlices()),new_hb.RouterSlices())
}

进行测试会发现,修改原始new_hb,new_new_hb会修改

    heartbeat_test.go:24: new_new_hb 4 4 [0x1022c2ed0 0x1022c2ed0 0x1022c2ed0 0x1022c2ed0]
    heartbeat_test.go:25: new_hb 3 4 [0x1022c2ed0 0x1022c2ed0 0x1022c2ed0]
    heartbeat_test.go:28: new_new_hb 4 4 [0x1022c2ed0 0x1022c2ed0 0x1022c2ed0 0x1022cc0e0]
    heartbeat_test.go:29: new_hb 4 4 [0x1022c2ed0 0x1022c2ed0 0x1022c2ed0 0x1022cc0e0]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions