std::unique_ptr<T,Deleter>::operator*, std::unique_ptr<T,Deleter>::operator-> - cppreference.com (original) (raw)
| (1) | (since C++11) (constexpr since C++23) | |
|---|---|---|
| pointer operator->() const noexcept; | (2) | (since C++11) (constexpr since C++23) |
operator* and operator-> provide access to the object owned by *this.
These member functions are only provided for unique_ptr for the single objects i.e. the primary template.
If get() is a null pointer, the behavior is undefined.
[edit] Return value
Returns the object owned by *this, equivalent to *get().
Returns a pointer to the object owned by *this, i.e. get().
[edit] Exceptions
- May throw if
pointerhas a throwing operator*.
[edit] Notes
The use of std::add_lvalue_reference is to make it possible to instantiate std::unique_ptr<void> since void& isn't allowed in C++ while std::add_lvalue_reference<void> produces void. See LWG673 for details.
[edit] Example
#include #include struct Foo { void bar() { std::cout << "Foo::bar\n"; } }; void f(const Foo&) { std::cout << "f(const Foo&)\n"; } int main() { std::unique_ptr ptr(new Foo); ptr->bar(); f(*ptr); }
Output:
[edit] Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 2762 | C++11 | operator* might be potentially-throwingeven if *get() was noexcept | added a conditionalexception specification |
| LWG 4148 | C++23 | operator* could return a dangling reference ifelement_type* differs from Deleter::pointer | the program is ill-formed in this case |
[edit] See also
| | returns a pointer to the managed object (public member function) [edit] | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |