在超出范围之后我遇到了析构函数的问题(它正在调用但是在一段时间之后需要在表单上进行操作,例如更改单选按钮),也许我的代码中存在错误.看一看:
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
EventLogger.Print += delegate(string output)
{ if (!textBox1.IsDisposed) this.Invoke(new MethodInvoker(() => textBox1.AppendText(output + Environment.NewLine)), null); };
}
private void button1_Click(object sender, EventArgs e)
{
TestClass test = new TestClass();
}
}
public static class EventLogger
{
public delegate void EventHandler(string output);
public static event EventHandler Print;
public static void AddLog(String TextEvent)
{
Print(TextEvent);
}
}
public class TestClass
{
public TestClass()
{
EventLogger.AddLog("TestClass()");
}
~TestClass()
{ …Run Code Online (Sandbox Code Playgroud) 做这样的事情是否安全:
char* charArray = new char[10];
strcat(charArray, "qwertyuiop");
charArray[3] = '\0';
delete [] charArray;
Run Code Online (Sandbox Code Playgroud)
一切都会被删除吗?或者之后的事情\0不会是什么?我不知道我是否要离开垃圾.
编辑:应该是 strcpy
很多时候,当我与人交谈时,他们正在重新使用(在DLL项目中)wstrings和字符串,因为它们比wchar_t数组消耗更多内存.怎么样?L"qweqweqweqweqwe"wchar_t数组是否需要比wstring更多的内存,或者它是不明显的?当我必须在Ansi和Unicode(很多new wchar_t temp和delete)之间进行转换时,我有点困惑
我遇到线程安全回调问题.
void draw_something() { /* draws something */ }
Run Code Online (Sandbox Code Playgroud)
问题是,如何draw_something在主应用程序线程中调用每个指定的时间量而不考虑其他代码(因此它将像主线程中的C#Timer和fire函数一样)?之前我使用CreateWindow创建(在主线程中)辅助窗口,它处理来自SendMessage的消息(从另一个定时器线程发送):
void MainThreadFunction(){
CreateThread(0, NULL, GoProc, NULL, NULL, NULL);
}
DWORD WINAPI GoProc(LPVOID lpParam){
while(1){
SendMessage(auxiliary_window_hWnd, ADDINATIONAL_MESSAGE, 0, 0);
Sleep(30);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以window的MessageQueue会处理safethread调用,但我不认为它是否是非常有效和优雅的方法.我知道有更好的方法(也许是提升?)但我不知道.
是否有可能做到这一点
std::string str(const char* s)
{
return std::string(s);
}
int main() {
char* strz = (char*)str("asd").c_str();
}
Run Code Online (Sandbox Code Playgroud)
代替:
int main(){
std::string temp = str("asd");
char* strz = (char*)temp.c_str();
}
Run Code Online (Sandbox Code Playgroud)
我知道它应该是,const char* strz但我只需要在代码块内(并且没有new/delete).从方法返回字符串后,它会查找引用(如果找不到它,删除字符串)然后调用c_str().我有很多char(独立于我),我可以使用第二种解决方案,但它需要太多的代码.
哪个代码好(如果好的话)
void DeleteObject(Object* obj)
{
delete obj;
}
Run Code Online (Sandbox Code Playgroud)
要么
void DeleteObject(Object** obj)
{
delete *obj;
}
int main()
{
Object *obj = new Object();
DeleteObject(&obj); or DeleteObject(obj);
}
Run Code Online (Sandbox Code Playgroud)
实际上DeleteObject功能不是那么短(它删除了对象字段).