[英]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.