【问题标题】:auto and const object自动和常量对象
【发布时间】:2012-01-21 14:35:09
【问题描述】:
#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&lt;int&gt; 而不是const shared_ptr&lt;const int&gt; getField 返回的类型?

编辑: MSVC2010

【问题讨论】:

标签: c++ constants auto


【解决方案1】:

auto 忽略引用和顶级consts。如果你想让他们回来,你必须这样说:

const auto v = a.getField();

请注意,getField 返回field_ 的副本。你确定不想引用const吗?

const shared_ptr<int>& getField () const;

auto& v = a.getField();

【讨论】:

  • 你为什么不写: const auto& v = a.getField(); ?
  • 因为在这种情况下会自动推断出const
  • 这可能会受益于一些澄清。从表面上看,如果我采用 const int&amp;,忽略参考 (const int) 和现在的顶级 const 我得到 int
  • 什么是不符合“顶级”条件的 const?
【解决方案2】:

在新的 C++11 标准中,我认为在此上下文中使用的 auto 关键字被编译器替换为 a.getField() 返回的任何类型。这是程序员的捷径。

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

【讨论】:

    猜你喜欢
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多