2014-03-30 42 views
0

我記得在某處讀過,但不能回想起哪裏,那運營商 - >是暫時的。它將通過operator->來查看對象,直到找到不是指針的東西,然後運行正常的操作符。在那。但是我遇到了這個問題,運營商 - >一致性和shared_ptr

考慮以下代碼:

#include <boost/shared_ptr.hpp> 
#include <vector> 
#include <iostream> 

struct Foo { 
    Foo(int val) : i(val) {} 
    typedef boost::shared_ptr<Foo> ptr; 
    int i; 
}; 

int main(int argc, char** argv) { 
    typedef std::vector<Foo::ptr> FooVec; 
    FooVec v; 
    for(FooVec::iterator it = v.begin(); it != v.end(); ++it) { 
     std::cout <<it->i <<std::endl; 
    } 
    return 0; 
} 

我得到這個錯誤:

ptr.cpp: In function ‘int main(int, char**)’: 
ptr.cpp:15:19: error: ‘class boost::shared_ptr<Foo>’ has no member named ‘i’ 
    std::cout <<it->i <<std::endl; 

由於一個boost :: shared_ptr的是不是一個指針。我可以不用編寫

std::cout <<(*it)->i <<std::endl 

解決這個問題,但我認爲這看上去差了很多,我試過的std :: shared_ptr的很好,但說了同樣的問題。有沒有解決這個問題的好方法,還是我堅持(*it)->i

+1

你被卡住了。你需要去引用迭代器*和智能指針。 – juanchopanza

+0

@ juanchopanza慚愧,感謝您的快速回復。那麼,人們是否會以其他方式解引用或者構建他們的代碼呢? – dutt

+1

無論如何,人們不應該使用指針「遍佈全球」。這包括智能指針。使用智能指針「遍佈全球」只比在各地使用原始指針略好一點。通過切換到智能指針類,不必要地使用動態分配並不會變得更好。 –

回答

0

I recall reading somewhere, can't recall where though, that operator-> is transient.

不在C++中。你需要像你已經發現的那樣去解引用。