[英]Creating an array of objects containing references
處理以下情況的最佳方法是什么?
假設我的行為應該像這樣
class Foo
{
public:
Foo(Bar& bar):m_bar(bar){}
private:
Bar& m_bar;
};
Foo:s必須有效引用Bar:s。 同樣,不同的Foo:s需要不同或相同的Bar:s。
我想將Foo:s存儲在數組中。 但是,由於Foo將需要非默認構造函數,因此它將不起作用。
我可以創建一個指向Foo:s的指針數組,但是隨后我需要為該數組中的每個對象調用new和delete。
我可以這樣定義Foo
class Foo
{
public:
void init(Bar& bar)
{
m_bar=&bar;
}
private:
Bar* m_bar;
};
,但是可以創建未初始化的Foo:s。
那么某種新的安置方式呢?
您可以仍然使用指針,但是可以使用unique_ptrs代替原始指針。 這些在c ++ 11中可用,但是如果您使用的是較舊的編譯器,則可以使用boost實現。
例如
class Foo
{
public:
Foo(unique_ptr<Bar> bar):m_pBar(bar){}
private:
unique_ptr<Bar> m_pBar;
};
這樣,您就不必擔心在Bar對象上調用delete,因為一旦不再有對它們的引用,它們就會被刪除。
然后你可以像這樣使用Foo
unique_ptr<Bar> pBar(new Bar());
Foo(pBar);
編輯:更改為使用unique_ptr而不是shared_ptr,並添加了示例用法
首先,對不起我的第一個回答,我把問題弄錯了。 我希望這是一個更好的解決方案:您可以在沒有默認構造函數的情況下創建元素vector
,如下所示:
#include <iostream>
#include <vector>
using namespace std;
class Foo
{
public:
Foo(int& bar): m_pBar(bar)
{ }
Foo& operator=(const Foo& other)
{ m_pBar = other.m_pBar; }
int Get()
{ return m_pBar; }
private:
int& m_pBar;
};
int main(int argc, char** argv)
{
int test[10] = { 0 };
vector<Foo> vect;
for (int& i: test)
vect.emplace_back(i);
test[0] = 1;
cout << vect[0].Get() << endl;
return 0;
}
最后,我使用以下構造函數實現了一個自定義容器:
template<class T>
template<class U,class V>
Array<T>::Array(unsigned int n,U source_iterator,const V& source_resource):memory(n*sizeof(T))
{
data=(T*)memory.pointerGet();
unsigned int k;
try
{
for(k=0;k<n;k++)
{
new(data+k)T(*source_iterator,source_resource);
++source_iterator;
}
}
catch(...)
{
while(k>0)
{
k--;
data[k].~T();
}
throw;
}
length=n;
capacity=n;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.