I am trying to create a member function that returns whether it has stored to shared_ptr
.
class X : public std::enable_shared_from_this {
...
bool is_shared() const {
return shared_from_this();
}
};
...
(new X())->is_shared(); // -> false?
Is this legal? In this case, is shared_from_this() guaranteed to return null and not throw any exception?
shared_from_this
can be used to obtain a shared_ptr
from an object that is already managed by a shared_ptr
.
Calling shared_from_this
on a non-shared object is undefined behavior in C++11.
However, in C++17 shared_from_this
will throw bad_weak_ptr
and you can catch this exception:
#include <memory>
#include <iostream>
class X : public std::enable_shared_from_this<X> {
public:
bool is_shared() const {
try {
shared_from_this();
return true;
} catch (std::bad_weak_ptr&) {
return false;
}
}
};
int main() {
X x;
std::cout << std::boolalpha << x.is_shared() << std::endl;
auto y = std::make_shared<X>();
std::cout << y->is_shared() << std::endl;
}
Output:
false
true
Furthermore you can use weak_from_this
to get access to weak_ptr
's expired
method:
bool is_shared() const {
return !weak_from_this().expired();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.