我有一個CRTP模板,我在其中使用了物件池。使用 generate() 靜態方法分配物件。
template <class tDerivedSignal, class tBridgeType, class tPayLoadType = void>
class SignalT : public SignalSignatureT<tBridgeType>
{
...
static tDerivedSignal &generate(tPayLoadType &fPayLoad)
{
tDerivedSignal &rtnVal = Pool::reserve();
// Copy pay load to signal instance
rtnVal.mPayLoad = fPayLoad;
// Return generated signal
return(rtnVal);
}
...
}
現在,問題是我不想阻止像
DerivedSignal sig = DerivedSignal::generate()
原因是副本sig可能具有本地范圍并變得無效/破壞,這將在用戶嘗試使用它時生成段錯誤。此外,分配的池物件將丟失并泄漏記憶體。我希望上面的復制賦值生成編譯時錯誤,但參考賦值如
DerivedSignal &sig = DerivedSignal::generate()
應該沒問題。我試圖洗掉 CRTP 模板中的賦值運算子,但沒有成功:
template <class tDerivedSignal, class tBridgeType, class tPayLoadType = void>
class SignalT : public SignalSignatureT<tBridgeType>
{
...
// Disable copy assignment operator to prevent a generated signal from being copied into
// a new instance that is not under pool management
tDerivedSignal operator=(const tDerivedSignal &) = delete;
tDerivedSignal operator=(const tDerivedSignal) = delete;
...
}
任何人有任何想法?
uj5u.com熱心網友回復:
您想洗掉 SignalT 復制分配(以及最有可能的復制構造)。默認情況下,任何繼承自 this 的類(如在您的 CRTP 模式中)也將洗掉其默認的復制建構式/復制賦值運算子,這也將禁止默認的移動構造/移動賦值運算子。
template <class tDerivedSignal, class tBridgeType, class tPayLoadType = void>
class SignalT : public SignalSignatureT<tBridgeType>
{
...
// Disable copy assignment operator to prevent a generated signal from being copied into
// a new instance that is not under pool management
void SignalT operator=(const SignalT&) = delete;
// You probably also want to delete copy construction
SignalT(SignalT const&) =delete;
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/333419.html
