C++ 自动和常量对象 #包括 #包括 使用名称空间std; 甲级 { 公众: 常量共享\u ptr getField()常量 { 返回字段; } 私人: 共享的ptr字段; }; 空f(常数A和A) { auto v=a.getField();//为什么auto不在这里共享常量? v、 reset();//确定:没有编译错误 } int main() { A A; f(a); std::cin.ignore(); }

C++ 自动和常量对象 #包括 #包括 使用名称空间std; 甲级 { 公众: 常量共享\u ptr getField()常量 { 返回字段; } 私人: 共享的ptr字段; }; 空f(常数A和A) { auto v=a.getField();//为什么auto不在这里共享常量? v、 reset();//确定:没有编译错误 } int main() { A A; f(a); std::cin.ignore(); },c++,constants,auto,C++,Constants,Auto,在上面的代码中,为什么编译器将v的类型推断为shared\u ptr,而不是将getField返回的类型推断为const shared\u ptr 编辑: MSVC2010auto忽略引用和顶级consts。如果你想让他们回来,你必须这么说: #include <iostream> #include <boost/shared_ptr.hpp> using namespace std; class A { public: const shar

在上面的代码中,为什么编译器将
v
的类型推断为
shared\u ptr
,而不是将getField返回的类型推断为
const shared\u ptr

编辑:
MSVC2010
auto
忽略引用和顶级
const
s。如果你想让他们回来,你必须这么说:

#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();
}
请注意,
getField
返回
字段的副本。您确定不需要对
常量的引用吗

const auto v = a.getField();
constshared\u ptr&getField()const;
auto&v=a.getField();

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


参见相关:为什么不写:const auto&v=a.getField()?因为在本例中,
const
是自动推断的。这可能得益于一些澄清。如果我取
常量int&
,忽略引用(
常量int
)和我得到的当前顶级常量
int
。什么是不符合“顶级”条件的常量?顶级常量:
const shared_ptr<int>& getField () const;

auto& v = a.getField();