使用 .get() 和 -> 运算符之间有区别吗?
Is there a difference between using .get() and the -> operator?
我正在学习 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 ):
typename std::add_lvalue_reference::type operator*() const; (1)
pointer operator->() const noexcept; (2)
Return value
1) Returns the object owned by *this, equivalent to *get().
2) Returns a pointer to the object owned by *this, i.e. get().
此外,举例来说(虽然人们永远不应该依赖 特定的 STL 实现),std::unique_ptr::get()
的定义及其 'equivalent' <memory>
header Visual Studio (MSVC) 版本中的 ->
运算符 相同:
_NODISCARD pointer get() const noexcept {
return _Mypair._Myval2;
}
_NODISCARD pointer operator->() const noexcept {
return _Mypair._Myval2;
}
.get()
在您的情况下不是必需的,因为 rec->draw()
将取消引用底层指针,因此您可以使用与原始指针具有相同语法的唯一指针。当您需要将唯一指针传递给以原始指针作为参数的函数时,.get()
是必需的。
除了内存管理之外,智能指针的设计在大多数方面都像原始指针一样。这样一来,只需进行最少的更改,它们就很容易被采用。特别是,它们被设计为使用与原始指针相同的语法来取消引用。这意味着您可以使用 rec->
代替 rec.get()->
,使用 *rec
代替 *(rec.get())
。
我正在学习 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 ):
typename std::add_lvalue_reference::type operator*() const; (1)
pointer operator->() const noexcept; (2)
Return value
1) Returns the object owned by *this, equivalent to *get().
2) Returns a pointer to the object owned by *this, i.e. get().
此外,举例来说(虽然人们永远不应该依赖 特定的 STL 实现),std::unique_ptr::get()
的定义及其 'equivalent' <memory>
header Visual Studio (MSVC) 版本中的 ->
运算符 相同:
_NODISCARD pointer get() const noexcept {
return _Mypair._Myval2;
}
_NODISCARD pointer operator->() const noexcept {
return _Mypair._Myval2;
}
.get()
在您的情况下不是必需的,因为 rec->draw()
将取消引用底层指针,因此您可以使用与原始指针具有相同语法的唯一指针。当您需要将唯一指针传递给以原始指针作为参数的函数时,.get()
是必需的。
除了内存管理之外,智能指针的设计在大多数方面都像原始指针一样。这样一来,只需进行最少的更改,它们就很容易被采用。特别是,它们被设计为使用与原始指针相同的语法来取消引用。这意味着您可以使用 rec->
代替 rec.get()->
,使用 *rec
代替 *(rec.get())
。