[wxWidgets]_[初级]_[发送异步事件的注意项之字符串深浅复制]


1.在工作线程和主线程进行通讯时,一般是通过发送事件来同步数据,而工作线程只能发送异步事件,基本不能发送界面绘制相关的同步事件。通讯数据时大多情况下需要传递字符串数值,这时候就需要先使用wxEvent的SetString方法,再使用QueueEvent.这里注意了,异步事件是对wxString有所有权的.


以下摘录wx.chm文档里的api说明.

QueueEvent() can be used for inter-thread communication from the worker threads to the main thread, it is safe in the sense that it uses locking internally and avoids the problem mentioned in AddPendingEvent() documentation by ensuring that the event object is not used by the calling thread any more. Care should still be taken to avoid that some fields of this object are used by it, notably any wxString members of the event object must not be shallow copies of another wxString object as this would result in them still using the same string buffer behind the scenes. For example:


wxCommandEvent 普通事件:

void FunctionInAWorkerThread(const wxString& str)
{
	wxCommandEvent* evt = new wxCommandEvent;

	// NOT evt->SetString(str) as this would be a shallow copy 浅复制,就是复制了计数器
	evt->SetString(str.c_str()); // make a deep copy 深复制,连数据一起创建了一个copy.

	wxTheApp->QueueEvent( evt );
}

wxThreadEvent 线程事件:

void FunctionInAWorkerThread(const wxString& str)
{
	wxThreadEvent evt;
	evt->SetString(str);

	// wxThreadEvent::Clone() makes sure that the internal wxString
	// member is not shared by other wxString instances:
	wxTheApp->QueueEvent( evt.Clone() );
}

2.wxString里面其实就是std::string,用std::string时也要注意点。

string( const string& s ); // a copy of the given string s, 浅复制

string( const char* str ); // a duplicate of str (optionally up to length characters long), 深复制


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Peter(阿斯拉达)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值