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();
}

In the above code why does the compiler deduce v's type as shared_ptr<int> and not as const shared_ptr<const int> the type returned by getField?

EDIT: MSVC2010

legends2k
  • 31,634
  • 25
  • 118
  • 222
Guillaume Paris
  • 10,303
  • 14
  • 70
  • 145

2 Answers2

8

auto ignores references and top level consts. If you want them back, you have to say so:

const auto v = a.getField();

Note that getField returns a copy of field_. Are you sure you dont want a reference to const?

const shared_ptr<int>& getField () const;

auto& v = a.getField();
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
0

In the new C++11 standard I think the auto keyword used in this context is substituted by the compiler for whatever type a.getField() returns. It's a shortcut for the programmer.

See http://en.wikipedia.org/wiki/C%2B%2B11#Type_inference

Jim Lahey
  • 84
  • 1
  • 2