为什么C2662错误没有't应用于对std::unique_ptr<B>对象
Why the C2662 error doesn't apply to a const reference to a std::unique_ptr<B> object?
我理解下面指出的错误C2662的原因。我的问题是为什么打电话main()
中的a.GetB()->Get()
不会产生类似的错误,因为GetB()
还返回了对unique_ptr<B>
对象的const
引用?
#include <iostream>
#include <memory>
using namespace std;
class B
{
int i;
public:
B(int j) : i(j) {}
int Get() { return i; }
};
class A
{
std::unique_ptr<B> uptrB;
public:
A(int i) : uptrB(new B(i)) {}
const std::unique_ptr<B>& GetB() { return uptrB; }
const B* GetB1() { return uptrB.get(); }
};
int main()
{
A a(3);
cout << a.GetB()->Get() << endl;
cout << a.GetB1()->Get() << endl; // error C2662:'B::Get' cannot conver 'this' pointer from 'const B' to 'B&'
}
const std::unique_ptr<B>
类似于B* const
,即指向可变B
的不可变指针,而不是指向不可变B
的可变指针const B*
。如果您想从unique_ptr
版本中得到相同的错误,则需要编写std::unique_ptr<const B>
。实际上,您是通过const
引用返回unique_ptr
,但它所引用的B
不是const
。
您正在从getB()
方法返回一个const引用。不能更改常量引用所指向的地址。然而,对返回的对象调用get()
会得到指针。这不是一件好事!
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 为什么 std::unique 不调用 std::sort?
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 在C++11中,将对象的所有权从一个unique_ptr转移到另一个unique _ptr
- 从自定义对象- std:unique的向量中消除重复项会导致崩溃