次のコードは、コピー コンストラクターが使用可能な場合にのみ機能します。
(経由で)printステートメントを追加std::cout
し、コピーコンストラクターを使用可能にすると、それは使用されません(不要なコピーを削除するためにコンパイラーのトリックが発生していると思います)。
しかし、出力operator <<
と以下の関数plop()
(一時オブジェクトを作成する場所) の両方で、コピー コンストラクターの必要性がわかりません。const 参照 (または私が間違っていること) ですべてを渡しているときに、言語がそれを必要とする理由を誰かが説明できますか?
#include <iostream>
class N
{
public:
N(int) {}
private:
N(N const&);
};
std::ostream& operator<<(std::ostream& str,N const& data)
{
return str << "N\n";
}
void plop(std::ostream& str,N const& data)
{
str << "N\n";
}
int main()
{
std::cout << N(1); // Needs copy constructor (line 25)
plop(std::cout,N(1)); // Needs copy constructor
N a(5);
std::cout << a;
plop(std::cout,a);
}
コンパイラ:
[Alpha:~/X] myork% g++ -v
組み込み仕様を使用。
ターゲット: i686-apple-darwin10
構成: /var/tmp/gcc/gcc-5646~6/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/ usr/lib --build=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1 --program-prefix=i686-apple-darwin10- --host=x86_64-apple- darwin10 --target=i686-apple-darwin10
スレッド モデル: posix
gcc バージョン 4.2.1 (Apple Inc. ビルド 5646)[Alpha:~/X] myork% g++ t.cpp
t.cpp: 関数 'int main()':
t.cpp:10: エラー: 'N::N(const N&)' はプライベート
t.cpp: 25: エラー: このコンテキスト内
t.cpp:10: エラー: 'N::N(const N&)' はプライベート
です t.cpp:26: エラー: このコンテキスト内
これは実際のコードの簡略版です。
実際のコードには、std::auto_ptr を含むクラスがあります。これは、const 参照を取るコピー コンストラクターが有効ではないことを意味し (何らかの作業がなければ)、そのためにコピー コンストラクターが使用できないことを示すエラーが発生していました。
クラスも変更します。
class N
{
public:
N(int) {}
private:
std::auto_ptr<int> data;
};
エラーは次のとおりです。
t.cpp:25: エラー: 'N::N(N)' の呼び出しに一致する関数がありません</p>