質問の問題は実際には存在しないため、問題を明確にする必要があります。
const foo y = x;
行はコンパイルされ、そのコピー コンストラクターで動作します。構築中の const オブジェクトは、コンストラクターが完了するまで「const」ではありません。したがって、構築中のオブジェクトが const であっても、コンストラクター本体はオブジェクトを変更できます。
また、この例のループは const であるすべてのものを変更していないことにも注意してください。配列は動的に割り当てられるため、オブジェクト自体が変更されていなくても、これらの配列要素は変更可能です。たとえばarr
、ctor が完了した後はポインターを変更できませんが、変更は可能arr[0]
です。
以下を試して、両方のポイントの動作を確認してください。
#include <stdio.h>
#include <algorithm>
class foo
{
int *arr; // arr holds numbers
int sz; // size of array
public:
foo() : arr(0), sz(0) { puts("default ctor");}
foo(int x) : arr(0), sz(x) {
puts( "int ctor");
arr = new int[sz];
for(int i=0;i<sz;i++)
arr[i]=0;
}
foo(const foo &f)
{
puts("copy ctor");
sz = f.sz;
arr = new int[sz];
for(int i=0;i<sz;i++)
arr[i]=f.arr[i];
}
~foo() {
delete [] arr;
}
foo& operator=(const foo& rhs) {
if (this != &rhs) {
foo tmp(rhs);
std::swap( arr, tmp.arr);
std::swap( sz, tmp.sz);
}
return *this;
}
void update() const {
for(int i = 0; i < sz; i++) {
arr[i] = arr[i] + 1;
}
}
void dump() const {
for(int i = 0; i < sz; i++) {
printf("%d ", arr[i]);
}
puts("");
}
};
int main()
{
foo x(5); //5 is size of array
const foo y = x;
y.dump();
y.update(); // can still modify the int array, even though `y` is const
y.dump();
}
const オブジェクトの構築と const メンバーを持つオブジェクトの構築を混同している可能性があると思います。これらのメンバーは初期化リストで初期化する必要があるためです。