boost::boost:的数组reference_wrapper未编译

boost::array of boost::reference_wrapper not compiling

本文关键字:boost 编译 wrapper reference 数组      更新时间:2023-10-16

我有一个boost::array类型的类,它存储对std::vector的引用。我想构建一个引用数组(我正在尝试DI,或者我认为是这样),但到目前为止还没有成功。

class RefHolder
{
public:
    boost::array<boost::reference_wrapper<std::vector<int> >, 3> sumsArray;
};
class OriginalHolder
{
public:
    OriginalHolder(boost::array<boost::reference_wrapper<std::vector<int> >, 3> & pSumsArray)
    {
        sumsArray[0] = boost::ref(_sums);
    }
private:
    std::vector<int> _sums;
}
int main()
{
    RefHolder ref;
    OriginalHolder original(ref.sumsArray);
    return 0;
}

我真的不明白编译器告诉我的。array甚至能和reference_wrapper一起工作吗?

C:/ide-4.6-workspace/chunkybacon/boost/boost/array.hpp:60: error: no matching function for call to 'boost::reference_wrapper<std::vector<int, std::allocator<int> > >::reference_wrapper()'
C:/ide-4.6-workspace/chunkybacon/boost/boost/ref.hpp:43: note: candidates are: boost::reference_wrapper<T>::reference_wrapper(T&) [with T = std::vector<int, std::allocator<int> >]
C:/ide-4.6-workspace/chunkybacon/boost/boost/ref.hpp:33: note:                 boost::reference_wrapper<std::vector<int, std::allocator<int> > >::reference_wrapper(const boost::reference_wrapper<std::vector<int, std::allocator<int> > >&)
C:/ide-4.6-workspace/chunkybacon/TEST/TEST.cc: In constructor 'RefHolder::RefHolder()':
C:/ide-4.6-workspace/chunkybacon/TEST/TEST.cc:6: note: synthesized method 'boost::array<boost::reference_wrapper<std::vector<int, std::allocator<int> > >, 3u>::array()' first required here 
C:/ide-4.6-workspace/chunkybacon/TEST/TEST.cc: In function 'int main()':
C:/ide-4.6-workspace/chunkybacon/TEST/TEST.cc:32: note: synthesized method 'RefHolder::RefHolder()' first required here
cc: C:/QNX641/host/win32/x86/usr/lib/gcc/i386-pc-nto-qnx6.4.0/4.3.3/cc1plus caught signal 1

当然,我可以只使用普通指针,它很有效,但我仍然有疑问,如果我能解决它,我宁愿使用引用。

我正在使用QNX 6.4.1和GCC 4.3.3。

提前感谢您的帮助=)

当您最初创建数组时,您有"空"条目。引用不能真的是空的(好吧,它可能是空的,但这是一个非常糟糕的主意),所以引用不能作为数组项工作。

请考虑改用boost::smart_ptr<vectorint> >。我意识到这并不完全是你想要的(指针与引用),但它很有效,这是对它有利的一大点。

------------对评论中问题的回应-------

不同之处在于,引用向量必须引用存在于其他地方的对象——管理这些对象的生存期并确保它们比引用它们的时间更长的地方

智能指针的矢量必须指向堆分配的对象,并管理这些对象的生存期。

这两种方法都有有效的用途。

boost::array的构造函数正试图用定义类型的默认构造函数初始化其所有成员,在本例中为boost::reference_wrapper,它没有默认构造函数,因为不能定义引用。