std::enable_shared_from_this

Medium Smart Pointers
Solve in Playground →

Problem Statement

Write a C++ program defining a class inheriting from `std::enable_shared_from_this` to safely generate a `std::shared_ptr` instance of `this`.

Input Format

A single integer N.

Output Format

Print value retrieved from shared pointer generated via `shared_from_this()`.

Constraints

-100000 <= N <= 100000

Sample Input

505

Sample Output

Value: 505, Use Count: 2

Explanation

`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.

Starter Code

#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;
}

Limits

  • Time Limit: 1s
  • Memory Limit: 256MB

Embedded C Programming

Updated: March 15, 2026
Intermediate

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