我無法將一個拷貝構造函數這個類: http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html如何向此類添加複製構造函數和賦值運算符?
我需要補充它,這樣我可以在STL vector容器添加concurrent_queue。 嘗試了下面,它幾乎編譯。實際上,如果我從複製構造函數中刪除the_mutex和the_condition_variable,它會進行編譯。當我將它添加回來時,它不會。關於編譯,賦值運算符似乎沒問題。
concurrent_queue(concurrent_queue<Data> const& rhs):
the_queue(rhs.the_queue),
the_mutex(rhs.the_mutex),
the_condition_variable(rhs.the_condition_variable)
{
}
concurrent_queue<Data>& operator = (concurrent_queue<Data> const& rhs)
{
if (this == &rhs) return *this; // check for self assignment
the_queue = rhs.the_queue;
the_mutex(rhs.the_mutex);
the_condition_variable(rhs.the_condition_variable);
}
我得到的錯誤是:
concurrentqueue.h: In copy constructor ‘concurrent_queue<Data>::concurrent_queue(const concurrent_queue<Data>&) [with Data = Packet*]’:
/usr/include/c++/4.4/bits/stl_construct.h:74: instantiated from ‘void std::_Construct(_T1*, const _T2&) [with _T1 = concurrent_queue<Packet*>, _T2 = concurrent_queue<Packet*>]’
/usr/include/c++/4.4/bits/stl_uninitialized.h:187: instantiated from ‘static void std::__uninitialized_fill_n<<anonymous> >::uninitialized_fill_n(_ForwardIterator, _Size, const _Tp&) [with _ForwardIterator = concurrent_queue<Packet*>*, _Size = long unsigned int, _Tp = concurrent_queue<Packet*>, bool <anonymous> = false]’
/usr/include/c++/4.4/bits/stl_uninitialized.h:223: instantiated from ‘void std::uninitialized_fill_n(_ForwardIterator, _Size, const _Tp&) [with _ForwardIterator = concurrent_queue<Packet*>*, _Size = long unsigned int, _Tp = concurrent_queue<Packet*>]’
/usr/include/c++/4.4/bits/stl_uninitialized.h:318: instantiated from ‘void std::__uninitialized_fill_n_a(_ForwardIterator, _Size, const _Tp&, std::allocator<_Tp2>&) [with _ForwardIterator = concurrent_queue<Packet*>*, _Size = long unsigned int, _Tp = concurrent_queue<Packet*>, _Tp2 = concurrent_queue<Packet*>]’
/usr/include/c++/4.4/bits/stl_vector.h:1035: instantiated from ‘void std::vector<_Tp, _Alloc>::_M_fill_initialize(size_t, const _Tp&) [with _Tp = concurrent_queue<Packet*>, _Alloc = std::allocator<concurrent_queue<Packet*> >]’
/usr/include/c++/4.4/bits/stl_vector.h:230: instantiated from ‘std::vector<_Tp, _Alloc>::vector(size_t, const _Tp&, const _Alloc&) [with _Tp = concurrent_queue<Packet*>, _Alloc = std::allocator<concurrent_queue<Packet*> >]’
test.cpp:18: instantiated from here
concurrentqueue.h:24: error: no match for call to ‘(boost::mutex) (boost::mutex&)’
編輯: 看來,升壓互斥繼承不可複製和條件變量,我認爲是一樣的。 有趣的是,在作業中我可以複製它。爲什麼甚至會編譯?我是否需要擔心在使用它的情況下,它在實踐中是不可複製的?
無需編寫其中的任何一個:編譯器無論如何都會發出代碼來複製成員方面的代碼,如果它是合法的話。你需要做的是寫*法律*代碼,如其他答案所示。 – EJP 2010-11-01 03:17:19