我有這樣一個一個結構:單張指針指向指針數組,並通過兩個C++
struct foo
{
IBar* ptr;
};
其爲具有長壽命的Foo對象的一部分。用戶通常會在不同的回調中獲得這些對象的實例,有時他們會在特定位置將內容注入IBar *,並在稍後的回調中使用它,最終將其釋放。 (IBar有virtual void free() { delete this; }
,當然可以重寫)。
問題是我想將我的用戶轉換爲每個foo結構有多個IBar*
的可能性,我想使轉換平滑。爲了使過渡平滑的一個想法是改變foo的結構如下:
struct foo
{
foo()
{
ptr = reinterpret_cast<IBar*>(new IBar*[N]);
memset(ptr, 0, sizeof(IBar*)*N);
}
IBar*& getBarPtr(size_t offset)
{
return reinterpret_cast<IBar**>(ptr)[offset];
}
IBar* ptr;
};
我的想法是這樣,使用老式的,他們希望有任何人只有一個IBar*
應該回退到使用第一在N
透明地使用它的通常方式:
someFoo.ptr = new iImplementIBar(...);
但那些誰開始過渡到新的使用用戶可以得到他們的偏移,而是做
someFoo.getBarPtr(myOffset) = new iImplementIBar(...);
的問題,不過,是foo
有reset
方法,用來做:
void reset() {
if (ptr)
{
ptr->free();
ptr = 0;
}
}
此想法與此代替:
void reset() {
IBar** ptrs = reinterpret_cast<IBar*>(ptr);
for (size_t i = 0; i < N; ++i)
if (ptrs[i])
{
ptrs[i]->free();
ptrs[i] = 0;
}
}
和free
在上面的功能似乎失去了。有沒有辦法做到這一點?或者出了什麼問題?
這只是毛病。爲什麼不嘗試更現代的C++構造,比如'std :: vector <>'和'std :: shared_ptr <>'? – GManNickG
-1對於攻擊性內容(我懷疑是一般的釣魚)。 –
這個想法是最終將它移動到一個合法的雙指針,它可以清潔。就像上面看起來那樣醜陋......它只是一個臨時過渡,重點是它儘可能地對圖書館的用戶是透明的。 –