在调用函子时删除它安全吗?
Is it safe to delete a functor while calling it?
假设我有以下代码:
typedef std::function<void ()> func_type;
void some_func()
{
// Irrelevant stuff here. Might take some time...
}
DWORD WINAPI thread_proc(LPVOID lpParameter)
{
func_type& func = *static_cast<func_type*>(lpParameter);
func();
return 0;
}
int main()
{
HANDLE handle;
{
std::function<void ()> my_func(some_func);
handle = ::CreateThread(NULL, 0, &thread_proc, &my_func, 0, NULL);
// Here we consider my_func won't be destroyed before its operator() is called in the other thread.
// I know nothing guarantees that, but let's just say it does for this sample.
}
::WaitForSingleObject(handle, INFINITE);
return EXIT_SUCCESS;
}
我目前的实现似乎工作,但这并不能证明我没有面临未定义行为。
这里my_func 可能在调用其operator()
返回之前被销毁。但是,既然我在some_func()
中没有提到my_func
,这真的是个问题吗?
注意:我不能使用std::thread
或boost::thread
不幸。我希望我能。
如果它在func()
发生之前被销毁,那么您正在无效对象上调用成员函数。您需要创建一个副本,该副本将至少在func()
调用之前有效。
这肯定是UB。你的评论是不正确的,没有什么可以保证在本地被销毁之前调用operator()
。事实上,我认为它很可能在新线程开始执行之前被销毁。这样做:
typedef std::function<void ()> func_type;
void some_func()
{
// Irrelevant stuff here. Might take some time...
}
DWORD WINAPI thread_proc(LPVOID lpParameter)
{
func_type* func = static_cast<func_type*>(lpParameter);
(*func)();
delete func;
return 0;
}
int main()
{
HANDLE handle;
{
func_type* my_func = new func_type(some_func);
handle = ::CreateThread(NULL, 0, &thread_proc, my_func, 0, NULL);
}
::WaitForSingleObject(handle, INFINITE);
return EXIT_SUCCESS;
}
相关文章:
- C++中的线程安全删除
- 逐字节删除 void* 是否安全?
- 线程调用的函数对对象删除是否安全?
- 从其存储的回调中删除 std::函数是否安全
- 将C 中的每个指针删除作为阵列的指针安全吗?
- 使用安全零内存新建/删除时出现问题
- 在特殊情况下使析构函数不是虚拟的,并删除基指针是否安全
- 调用不访问已删除对象中的任何类成员的类方法是否安全
- 通过 const_cast 删除 const 并调用不修改结果对象的非 const 函数是否安全?
- 通过指向其基的指针删除 POD 对象是否安全
- 在迭代地图时向/从地图添加/删除元素是否安全
- 在这里删除 c++ 易失性是否安全
- C++安全对象删除
- 调用remove()删除析构函数中的文件是否安全
- 删除函数中的对象:丑陋、容易出错、效率低下,而且通常不安全
- 从代码中删除SAL注释是否安全
- 如何安全删除QT::QTcpSocket
- dynamic_casting后删除指针是否安全
- 删除链接列表是否安全
- 如何检测指针是否已删除并安全删除