Write a C++ program defining a class inheriting from `std::enable_shared_from_this` to safely generate a `std::shared_ptr` instance of `this`.
A single integer N.
Print value retrieved from shared pointer generated via `shared_from_this()`.
-100000 <= N <= 100000
505
Value: 505, Use Count: 2
`std::enable_shared_from_this` enables an object managed by a `std::shared_ptr` to safely create additional `std::shared_ptr` instances pointing to itself.
#include <iostream>
#include <memory>
class Node : public std::enable_shared_from_this<Node> {
private:
int val;
public:
Node(int v) : val(v) {}
std::shared_ptr<Node> getptr() {
// Return shared_from_this here
}
int getVal() const { return val; }
};
int main() {
int n;
if (std::cin >> n) {
auto sp1 = std::make_shared<Node>(n);
auto sp2 = sp1->getptr();
std::cout << "Value: " << sp2->getVal() << ", Use Count: " << sp1.use_count() << "n";
}
return 0;
}Embedded systems rely on efficient low-level programming to interact directly with hardware. In this course, you will learn how to write practical Embedded C programs used in real microcontroller-based systems. Rather than focusing only on theory, this course follows a practice-driven approach. Each lesson includes hands-on coding exercises that simulate real firmware development tasks used