C++ プロジェクトに取り組んでいるときに、予期しないイライラする動作に遭遇しました。私の実際のコードはもう少し複雑ですが、次の例でも同様にキャプチャされます。
class Irritating
{
public: Irritating() {}
private: Irritating(const Irritating& other) {}
};
const Irritating singleton; // Works just fine.
const Irritating array[] = {Irritating()}; // Compilation error.
int main()
{
return 0;
}
これをコンパイルしようとすると、次のエラーが発生します (念のため GCC バージョンがスローされます)。
[holt@Michaela irritating]$ g++ --version
g++ (GCC) 4.6.3 20120306 (Red Hat 4.6.3-2)
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[holt@Michaela irritating]$ g++ test.cpp
test.cpp:4:11: error: ‘Irritating::Irritating(const Irritating&)’ is private
test.cpp:8:41: error: within this context
[holt@Michaela irritating]$
残念ながら、問題のオブジェクトは外部ライブラリからのものであり、私の管理外です。私の現在の回避策は、ポインターの配列を使用することです。動作しますが、少しハックな感じがし、不必要な間接レイヤーが追加されます。これを行うより良い方法はありますか?
また、配列は一定でグローバルです(実際のコードではクラス静的です)。その場で初期化されていないのはなぜですか?これは予想される C++ の動作ですか、それとも GCC のバグ/癖ですか?
更新: GCCに同意するかどうかを確認するためだけにClangをインストールしました。悲しいことに、それはしました:
[holt@Michaela irritating]$ clang test.cpp
test.cpp:8:29: warning: C++98 requires an accessible copy constructor for class 'Irritating' when binding a reference to a temporary; was private
[-Wbind-to-temporary-copy]
const Irritating array[] = {Irritating()};
^
test.cpp:4:11: note: declared private here
private: Irritating(const Irritating& other) {}
^
test.cpp:8:29: error: calling a private constructor of class 'Irritating'
const Irritating array[] = {Irritating()};
^
test.cpp:4:11: note: declared private here
private: Irritating(const Irritating& other) {}
^
1 warning and 1 error generated.
[holt@Michaela irritating]$