Re: assignment of const class members
On Dec 21, 4:47 am, Kira Yamato <kira...@earthlink.net> wrote:
On 2007-12-21 03:38:33 -0500, hweek...@yahoo.com said:
hi,
it seems i can't assign the const variable u in class A, one way to
solve the problem may be to build a copy constructor. however, why
does C++ or vector class not like this code? my g++ is: gcc version
4.0.1 (Apple Inc. build 5465). thanks for the help.
summary of compile error:
---------------------------------------
cpp.C:4: error: non-static const member 'const unsigned int A::u',
can't use default assignment operator
/usr/include/c++/4.0.0/bits/vector.tcc:260: warning: synthesized
method 'A& A::operator=(const A&)' first required here
code:
-------
1
2 #include <vector>
3
4 struct A {
5 A(const unsigned int a) : u(a) { }
6 private: const unsigned int u;
7 };
8
9 int main () {
10
11 std::vector<A> y;
12 y.push_back(A(2));
13 }
You have a number of problems with this code.
First, when (12) is executed, std::vector tries to allocate an array of
struct A. Unfortunately, struct A has no default constructor. So, it
cannot construct each element in the array.
There is no array, he's trying to copy into the empty vector a single
element.
if he had written the following:
std::vector<A> y(10);
only then would a default ctor be required.
Second, std::vector will then try to assign A(2) to one of the
available entry in the newly allocated array. Unfortunately, you did
not provide an assignment operator, so the default one kicks in.
Furthermore unfortunate, the default assignment operator tries to copy
the const member u, and you cannot change const members. This is the
error message you are seeing below.
full compile error:
-------------------------
[16:34]:Macintosh:tmp 7+ g++ cpp.C
cpp.C: In member function 'A& A::operator=(const A&)':
cpp.C:4: instantiated from '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>]'
/usr/include/c++/4.0.0/bits/stl_vector.h:610: instantiated from
'void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = A,
_Alloc = std::allocator<A>]'
cpp.C:12: instantiated from here
cpp.C:4: error: non-static const member 'const unsigned int A::u',
can't use default assignment operator
/usr/include/c++/4.0.0/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>]':
/usr/include/c++/4.0.0/bits/vector.tcc:260: warning: synthesized
method 'A& A::operator=(const A&)' first required here
--
-kira