how to deal with deallocation of copied pointers
我正在尝试使用C ++中的构造函数和析构函数来构建结构(这是一件不好的事吗?我应该使用类吗?),因为我讨厌每次编写10条删除struct.member时都不需要成员应被释放
该结构的成员主要是指向其他类型的指针。
但是,除了将成员指针设为唯一指针之外,我还希望能够将另一个指针的副本分配给该结构中的成员指针。因此,如果我尝试在该结构的析构函数内释放该内存,则该内存可能已经被释放,从而导致崩溃。 (尤其是如果复制的指针来自相同结构的另一个对象)
将ptr转换为ptr-types而不是struct中的ptr-types都不会解决问题(我认为),因为我还希望允许成员能够成为指向对象的唯一指针。
我想到的一种可能的解决方案是同时拥有一个ptr-to-ptr和一个ptr-to-ptr指向的ptr。但这将是相当低效的。
我最好的解决方案是什么?
我希望(但有疑问)我的问题很清楚。
这是一些可能有用的示例代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | struct GraphicsDesc { public: ID3D11VertexShader* pSolidColorVS; ID3D11PixelShader* pSolidColorPS; ID3D11InputLayout* pInputLayout; ID3D11ShaderResourceView* pColorMap; ID3D11SamplerState* pSampler; ID3D11BlendState* pBlendState; ID3D11Buffer* pVertexBuffer; UINT VertexSize; D3D_PRIMITIVE_TOPOLOGY Topology; GraphicsDesc() { pSolidColorVS = nullptr; pSolidColorPS = nullptr; pInputLayout = nullptr; pColorMap = nullptr; pSampler = nullptr; pBlendState = nullptr; pVertexBuffer = nullptr; VertexSize = 0; Topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; } virtual ~GraphicsDesc() { if (pVertexBuffer) { pVertexBuffer->Release(); } if (pBlendState) { pBlendState->Release(); } if (pSampler) { pSampler->Release(); } if (pColorMap) { pColorMap->Release(); } if (pInputLayout) { pInputLayout->Release(); } if (pSolidColorPS) { pSolidColorPS->Release(); } if (pSolidColorVS) { pSolidColorVS->Release(); } } }; |
所有这些指针数据成员都是指向引用计数的COM类型的指针。
您应该使用