2012-01-21 9 views
3
#include <iostream> 
#include <boost/shared_ptr.hpp> 

using namespace std; 

class A 
{ 

    public: 
     const shared_ptr<const int> getField() const 
     { 
      return field_; 
     } 

    private: 
     shared_ptr<int> field_; 
}; 

void f(const A& a) 
{ 
    auto v = a.getField(); //why auto doesn't a const shared_ptr<const int> here ? 
    v.reset(); //OK: no compile error 
} 

int main() 
{ 
    A a; 
    f(a); 
    std::cin.ignore(); 
} 

はなぜコンパイラはvの種類shared_ptr<int>などとのgetFieldによって返さないconst shared_ptr<const int>としてタイプを推測しますか?自動車とconstオブジェクト

EDIT: MSVC2010

+0

を参照してください? –

+2

関連:http://stackoverflow.com/questions/7138588/c0x-auto-what-if-itit-a-constant-reference –

答えて

7

auto参照して、トップレベルconst秒を無視します。

const auto v = a.getField(); 

注意をgetFieldfield_のコピーを返すこと:あなたが戻ってそれらをしたい場合は、そう言っています。あなたはconstへの参照をしたくないですか?私はこの文脈で使用autoキーワードがどんなタイプa.getField()リターンのために、コンパイラによって置換されていると思う新しいC++ 11標準で

const shared_ptr<int>& getField() const; 

auto& v = a.getField(); 
+0

なぜあなたは次のように書くのですか?const auto&v = a.getField(); ? – Guillaume07

+0

この場合、 'const'が自動的に推測されるためです。 – fredoverflow

+0

ok ...間違いなくC++は微妙なラングである! – Guillaume07

関連する問題