Spec-Zone.ru › C++

std::shared_ptr<T>::operator bool

explicit operator bool() const noexcept;
(constexpr since C++26)

Checks if *this stores a non-null pointer.

Return value

get() != nullptr

Notes

An empty shared_ptr (where use_count() == 0) may store a non-null pointer accessible by get(), e.g. if it were created using the aliasing constructor.

Example

#include <iostream>
#include <memory>

void report(std::shared_ptr<int> ptr) 
{
    if (ptr)
        std::cout << "*ptr = " << *ptr << "\n";
    else
        std::cout << "ptr is not a valid pointer.\n";
}

int main()
{
    std::shared_ptr<int> ptr;
    report(ptr);
    
    ptr = std::make_shared<int>(7);
    report(ptr);
}

Output:

ptr is not a valid pointer.
*ptr=7

See also

get
returns the stored pointer
(public member function)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/memory/shared_ptr/operator_bool

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API