我正在做一些C ++测试的研究,问题之一如下:
std::unique_ptr<Rectangle> rec = std::make_unique<Rectangle>(0, 0, 15, 15);
// why must we use rec.get()->?
rec.get()->setWidth(30);
rec.get()->draw();
我想知道的是为什么我们需要.get()
这里?如果我省略.get()
,是否会一样呢:
rec->setWidth(30);
rec->draw();
根据cppreference,使用->
运算符等同于使用get()
函数(以下引用中的情况2):
类型名称std :: add_lvalue_reference :: type运算符*()const; (1)
指针操作符->()const noexcept; (2)
返回值
1)返回* this拥有的对象,等效于* get()。
2)返回指向* this拥有的对象的指针,即get()。
此外,通过示例(尽管不应依赖于STL的特定实现),标头的Visual Studio(MSVC)版本中的定义std::unique_ptr::get()
及其“等效”->
运算符<memory>
是相同的:
_NODISCARD pointer get() const noexcept {
return _Mypair._Myval2;
}
_NODISCARD pointer operator->() const noexcept {
return _Mypair._Myval2;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句