Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto and const object

#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

like image 592
Guillaume Paris Avatar asked Jan 24 '26 21:01

Guillaume Paris


1 Answers

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();
like image 175
fredoverflow Avatar answered Jan 26 '26 11:01

fredoverflow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!