有人使用共享指標來確保上述句柄在不再需要時被銷毀。
在實踐中,實作對InitDemoStruct() DestroyStruct() struct DemoStruct我來說是不透明的。它們是由其他人提供的。
盡管此代碼片段按預期作業,但確實看起來很奇怪:
通常可以看到智能指標指向特定的類或結構,例如:std::shared_ptr<struct DemoSt> ptr2object; 最近看到這樣的用法。使用智能指標指向特定類或結構的指標,例如:std::shared_ptr<struct DemoSt*> ptr2point_of_object;
更新:有一個答案提供nwp。
這是前面提到的代碼片段:
#include <memory>
#include <iostream>
struct DemoStruct;
using DemoStructHandle = DemoStruct* ;
//In practice, the implementation of `InitDemoStruct()` `DestroyStruct()` `struct DemoStruct` is opaque to me.
//They are provided by others.
struct DemoStruct{
};
void InitDemoStruct(DemoStructHandle* handle_ptr){
*handle_ptr = new DemoStruct();
//may do some other meaningful init in InitDemoStruct();
};
void DestroyStruct(DemoStructHandle* handle_ptr){
std::cout << "Destroy() is called" << std::endl;
if(handle_ptr==nullptr){
return;
}
delete *handle_ptr;
}
//I use shared pointer to ensure that the aforementioned handle is destroyed when it's no longer needed.
std::shared_ptr<DemoStructHandle> MakeDemoStructHandlePtr(void)
{
return std::shared_ptr<DemoStructHandle>(new DemoStructHandle(nullptr), [](DemoStructHandle* pHandle){
DestroyStruct(pHandle);
delete pHandle;});
}
int main()
{
std::shared_ptr<DemoStructHandle> demo_class_handle_ptr = MakeDemoStructHandlePtr();
InitDemoStruct(demo_class_handle_ptr.get());
}
uj5u.com熱心網友回復:
這看起來像一個圍繞 C 不透明句柄的 C 包裝器。
在一個檔案中,這很奇怪,但是什么時候DemoStructHandle是唯一完整的型別,你(故意)不能做得更好。
uj5u.com熱心網友回復:
我的答案:
class Wrarper_without_smartptr
{
public:
Wrarper_without_smartptr(){
InitDemoStruct(&handle);
}
Wrarper_without_smartptr(const Wrarper_without_smartptr&) = delete;
Wrarper_without_smartptr operator=(const Wrarper_without_smartptr&)= delete;
~Wrarper_without_smartptr(){
DestroyStruct(&handle);
}
private:
DemoStructHandle handle;
};
uj5u.com熱心網友回復:
我假設您的問題是如何避免雙重間接(指標對指標)。你可以這樣做:
std::shared_ptr<DemoStruct> MakeDemoStructPtr(/*void not required in C */)
{
DemoStruct *pHandle;
InitDemoStruct(&pHandle);
return std::shared_ptr<DemoStruct>(pHandle,
[](DemoStruct *pHandle){
DestroyStruct(&pHandle);
}
);
}
int main()
{
std::shared_ptr<DemoStruct> demo_class_handle_ptr = MakeDemoStructPtr();
}
shared_ptr 指向 DemoStruct 而不是指向 DemoStructHandle。
如果InitDemoStruct有更多引數,您可以將引數添加到MakeDemoStructPtr
uj5u.com熱心網友回復:
我會使用shared_ptr這樣的:
struct DemoStructDeleter {
void operator()(DemoStructHandle p) {
DemoStructDestroy(&p);
}
};
// in some function:
DemoStructHandle h;
InitDemoStruct(&h);
std::shared_ptr<DemoStruct> smartptr(h, DemoStructDeleter{});
// do something with smartptr
請注意,它不是shared_ptr<DemoStructHandle>,因為您不希望有一個指向句柄的智能指標,而是指向結構本身。
如果將其包裝在工廠函式中,則不需要顯式DemoStructDeleter,但可以使用 lambda 函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/451148.html
上一篇:VSCode撰寫回圈
