您的位置:首页 > 其它

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

2013-04-28 01:02 239 查看
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), 深复制
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: