#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();
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,为什么编译器推断出v的类型shared_ptr<int>而不是const shared_ptr<const int>getField返回的类型?
编辑: MSVC2010
auto忽略引用和顶级consts.如果你想要它们,你必须这样说:
const auto v = a.getField();
Run Code Online (Sandbox Code Playgroud)
请注意,getField返回一份副本field_.你确定你不想参考const吗?
const shared_ptr<int>& getField () const;
auto& v = a.getField();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1439 次 |
| 最近记录: |