Skip to main content

std::unique_ptr<T,Deleter>::operator*, std::unique_ptr<T,Deleter>::operator->

Since C++11
typename std::add_lvalue_reference<T>::type operator*() const
noexcept(noexcept(*std::declval<pointer>()));

pointer operator->() const noexcept;
Since C++23
typename std::add_lvalue_reference<T>::type operator*() constexpr
noexcept(noexcept(*std::declval<pointer>()));

pointer operator->() constexpr noexcept;

operator* and operator-> provide access to the object owned by *this.

The behavior is undefined if get() == nullptr.

These member functions are only provided for unique_ptr for the single objects i.e. the primary template.

Parameters

(none)

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().

Exceptions

1)

May throw if pointer has a throwing operator*.

Example

#include <iostream>
#include <memory>

struct Foo {
void bar() { std::cout << "Foo::bar\n"; }
};

void f(const Foo&)
{
std::cout
<< "f(const Foo&)\n";
}

int main()
{
std::unique_ptr<Foo> ptr(new Foo);

ptr->bar();
f(*ptr);
}
Result
Foo::bar
f(const Foo&)

std::unique_ptr<T,Deleter>::operator*, std::unique_ptr<T,Deleter>::operator->

Since C++11
typename std::add_lvalue_reference<T>::type operator*() const
noexcept(noexcept(*std::declval<pointer>()));

pointer operator->() const noexcept;
Since C++23
typename std::add_lvalue_reference<T>::type operator*() constexpr
noexcept(noexcept(*std::declval<pointer>()));

pointer operator->() constexpr noexcept;

operator* and operator-> provide access to the object owned by *this.

The behavior is undefined if get() == nullptr.

These member functions are only provided for unique_ptr for the single objects i.e. the primary template.

Parameters

(none)

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().

Exceptions

1)

May throw if pointer has a throwing operator*.

Example

#include <iostream>
#include <memory>

struct Foo {
void bar() { std::cout << "Foo::bar\n"; }
};

void f(const Foo&)
{
std::cout
<< "f(const Foo&)\n";
}

int main()
{
std::unique_ptr<Foo> ptr(new Foo);

ptr->bar();
f(*ptr);
}
Result
Foo::bar
f(const Foo&)