2008年1月20日日曜日

コピーコンストラクタ

class Value {
private:
int value;
public:
Value(int value = 0) {
this->value = value;
}
Value(Value& value) {
this->value = value.value;
}
};

int main(int argc, char** argv) {
Value a = Value(1);
return 0;
}


このコードをコンパイルすると

$ g++ -Wall test.cpp
test.cpp: In function 'int main(int, char**)':
test.cpp:44: error: no matching function for call to 'Value::Value(Value)'
test.cpp:11: note: candidates are: Value::Value(Value&)
test.cpp:7: note: Value::Value(int)


って怒られる。

使ってるgccは以下。

$ g++ -Wall test.cpp
$ g++ -v
Using built-in specs.
Target: i686-apple-darwin8
Configured with: /private/var/tmp/gcc/gcc-5250.obj~20/src/configure --disable-checking -enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.0/ --with-gxx-include-dir=/include/c++/4.0.0 --build=powerpc-apple-darwin8 --with-arch=pentium-m --with-tune=prescott --program-prefix= --host=i686-apple-darwin8 --target=i686-apple-darwin8
Thread model: posix
gcc version 4.0.1 (Apple Computer, Inc. build 5250)


どうも、テンポラリオブジェクトがconstで作成されてるみたい。

 Value(const Value& value) {
this->value = value.value;
}


みたく、コピーコンストラクタの引数をonst referenceにすればOK、というか、そうすべきみたい。

0 件のコメント: