重複の可能性:
演算子のオーバーロード ->
やあ、
評価後に連鎖(再適用)されるのを見てきました。operator->()
たとえば、次のようになります。
struct Bar
{
Bar() : m_str("Hello world!") {}
const string* operator->() const { return &m_str; }
string m_str;
};
struct Foo
{
const Bar& operator->() const { return m_bar; }
Bar m_bar;
};
int main()
{
Foo f;
cout << f->c_str() << endl;
return 0;
}
これには、3 つを評価する必要がありoperator->()
ます - Foo::operator->()
、Bar::operator->()
および通常のポインター解決。
ただし、途中でポインターを使用すると機能しFoo::operator->()
ません。参照ではなくバーへのポインターを返すと、コンパイルされません。auto_ptr<auto_ptr<string>>
たとえば、同じことが起こります。
非過負荷に固有なoperator->()
ので、一度だけ適用され、連鎖は発生しませんか? を使用せずに以下のコードを動作させることは可能(*ptr2)-> ...
ですか?
int main()
{
string s = "Hello world";
auto_ptr<string> ptr1(&s);
auto_ptr<auto_ptr<string> > ptr2(&ptr1);
cout << ptr1->c_str() << endl; // fine
cout << ptr2->c_str() << endl; // breaks compilation
}
ありがとう!