marunomaruno-memo

marunomaruno-memo

[C++][STL] vector にオブジェクトを入れるときのクラスの注意点

2012年09月14日 | Android
■ [C++][STL] vector にオブジェクトを入れるときのクラスの注意点

・vector にオブジェクトを入れるときに、そのコピーコンストラクターの引数は const でなければならない。
const にしないとビルドエラーになる。
うっかり付け忘れても、普通に使っている分には問題ないかもしれないが、vector なんかに入れようとすると怒られる。

ついでに、vector に入れるためには、コピーコンストラクターだけではなく、引数のないコンストラクター、デストラクターが必要。また、自分でコピーコンストラクターを作らないといけない状況の場合は、代入演算子のオーバーロードも必要になってくる。

そういえば、前、関係演算子(== や <) もオーバーロードが必要なものがあったような、なかったような。。。vector の場合は、なくても平気かな。


□ vector_sample.cpp
---
#include <iostream>
#include <vector>
using namespace std;

class A {
public:
    A() {}
    A(A& r) {}    // A(const A& r) ならOK
};

int main() {
    vector<A> v;
    v.push_back(A());    // no matching function for call to `A::A(A)'
to `A::A(const A&)'
    return 0;
}
---


□ ビルド結果
---

**** Build of configuration Debug for project vector_sample ****

**** Internal Builder is used for build               ****
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o src/vector_sample.o ../src/vector_sample.cpp
../src/vector_sample.cpp: In function `int main()':
../src/vector_sample.cpp:21: error: no matching function for call to `A::A(A)'
../src/vector_sample.cpp:16: note: candidates are: A::A(A&)
C:/MinGW/bin/../lib/gcc/mingw32/3.4.2/../../../../include/c++/3.4.2/bits/stl_construct.h: In function `void std::_Construct(_T1*, const _T2&) [with _T1 = A, _T2 = A]':
C:/MinGW/bin/../lib/gcc/mingw32/3.4.2/../../../../include/c++/3.4.2/bits/stl_vector.h:560:   instantiated from `void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = A, _Alloc = std::allocator<A>]'
../src/vector_sample.cpp:21:   instantiated from here
C:/MinGW/bin/../lib/gcc/mingw32/3.4.2/../../../../include/c++/3.4.2/bits/stl_construct.h:81: error: no matching function for call to `A::A(const A&)'
../src/vector_sample.cpp:16: note: candidates are: A::A(A&)
../src/vector_sample.cpp:15: note:                 A::A()
C:/MinGW/bin/../lib/gcc/mingw32/3.4.2/../../../../include/c++/3.4.2/bits/vector.tcc: In member function `void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = A, _Alloc = std::allocator<A>]':
C:/MinGW/bin/../lib/gcc/mingw32/3.4.2/../../../../include/c++/3.4.2/bits/stl_vector.h:564:   instantiated from `void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = A, _Alloc = std::allocator<A>]'
../src/vector_sample.cpp:21:   instantiated from here
C:/MinGW/bin/../lib/gcc/mingw32/3.4.2/../../../../include/c++/3.4.2/bits/vector.tcc:234: error: no matching function for call to `A::A(const A&)'
../src/vector_sample.cpp:16: note: candidates are: A::A(A&)
Build error occurred, build is stopped
Time consumed: 1047  ms.  
---

                                                                        以上