Hi folks, I was building a personal project this weekend and ended up using a lot of smart pointers in C++. Ive noticed that many people find them confusing at first, so here’s a simple way I think about them: 1. std::unique_ptr Use this when there is clear, single ownership. The object’s lifetime is tied to one owner, and ownership can be transferred using std::move. 2. std::shared_ptr Use this when multiple parts of your system need to share ownership of an object. The object lives until the last reference is released, preventing premature deletion. Be careful though cyclic references can lead to memory leaks. 3. std::weak_ptr A non-owning reference to an object managed by shared_ptr. It does not affect the object’s lifetime and is mainly used to break cyclic dependencies. Still exploring more real-world patterns around this. Would love to hear how others approach this. #cpp #multithreading #systemsprogramming
Smart Pointers in C++: std::unique_ptr, std::shared_ptr, std::weak_ptr
More Relevant Posts
-
🎯 MY APPROACH 1️⃣ Here, first of all I check whether a number n is positive or not if it is positive then we can proceed. 2️⃣ In the next expression, we simply check whether it is the power of two or not. 3️⃣ Then I combine both the expression by using logical AND operator. 4️⃣ To check whether a number is power of two or not. We simply anding a number n with the very number decrement by one and check if it returns 0 as an output then it is power of two otherwise not. 5️⃣ Atlast, we return the combined expression. #LeetCode #cp_sheet #BitManipulation #LeetcodeSolution #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
Most people think "new" just creates an object. It actually does two things. When you write: int* p = new int(10); It: • Allocates memory • Constructs the object But what if you already have memory? And only want to construct an object there? That’s where placement new comes in. char buffer[sizeof(int)]; int* p = new (buffer) int(10); Here: • No memory allocation happens • The object is constructed inside existing memory This means: Allocation and construction are actually separate steps in C++. Why this matters: • Custom memory management • Object pools • Performance-critical systems But there’s a catch. You are responsible for: • Managing the memory • Calling the destructor manually This is not something you use every day. But it shows how much control C++ gives over memory and object lifetimes. Didn’t expect this level of control at first — kinda blew my mind. #cpp #cplusplus #systems #softwareengineering #programming
To view or add a comment, sign in
-
CppCon, The C++ Conference 2025 Sergey Dobychin: "Constexpr STL Containers: Why C++20 Still Falls Short" youtu.be/Py4GJaCHwkA One of the most powerful features that sets C++ apart from many other languages is its ability to perform complex constant evaluation at compile time using constexpr. With each new language standard, these capabilities have expanded — and C++20 took a big step forward by allowing dynamic memory allocation in constexpr functions via operator new. This made it possible, for example, to use containers like std::vector and std::string in constexpr code. However, there’s still a key limitation: you can only use these containers in constexpr functions — not as top-level constexpr objects. That means you can't declare a constexpr std::vector or std::string at global scope and use it later in runtime without overhead for initialization. The language still doesn’t fully support top-level dynamic containers in constant expressions. In this talk, I’ll explore the current state of constant evaluation in modern C++, with a special focus on dynamic memory allocation in constexpr contexts. I’ll walk through the limitations in C++20 and show how you can go beyond them by implementing a custom allocator that enables truly compile-time std::vector, std::string, and other STL containers, which will become fully supported as constexpr in future standards, thus opening the door to more powerful and flexible compile-time programming. --- Sergey Dobychin Sergey worked in systems programming at Kaspersky Lab. Currently, he is developing desktop applications in C++.
Constexpr STL Containers: Why C++20 Still Falls Short - Sergey Dobychin - CppCon 2025
https://www.youtube.com/
To view or add a comment, sign in
-
🚀 uint32_t vs unsigned int — What’s the difference? If you're writing embedded code, knowing the difference is important. Here’s a simple breakdown 👇 🔹 uint32_t → Defined in "stdint.h" and always 32-bit 🔹 unsigned int → Built-in C type, size can depend on compiler 💡 Simple rule: Need exact 32 bits? Use uint32_t General use? unsigned int can work. ✅ Use uint32_t for: - Registers - CAN/SPI/UART data - Portable code ✅ Use unsigned int for: - Counters - General variables ⚠️ When size matters → use uint32_t Small difference… but important in embedded C. #EmbeddedSystems #CProgramming #Firmware #STM32 #EmbeddedC
To view or add a comment, sign in
-
Logging in C++ shouldn’t be unstructured and hard to trace. With Vix, you get contextual and structured logs out of the box: request id, module, fields, everything in one place. Clear logs. Real debugging. https://lnkd.in/d2C3CyjP
To view or add a comment, sign in
-
-
Day 20 / 90 — Software Engineering Challenge Today was focused on understanding bit manipulation and binary operations. DSA Practice (Bit Manipulation) Solved problems on: • Check if the i-th bit is set or not • Check if a number is odd or even • Check if a number is a power of 2 • Count the number of set bits • Set/Unset the rightmost unset bit • Swap two numbers using XOR • Divide two numbers without using multiplication or division Bitwise operations can significantly optimize computations XOR has unique properties useful for swapping and comparisons Checking powers of 2 becomes simple using bit tricks Binary representation helps in understanding how data is processed at a low level Bit manipulation may look simple, but it’s extremely powerful for writing efficient code. Exploring deeper into how things work at the binary level. #90DaysOfCode #DSA #BitManipulation #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
C++26 is here, and it’s a game changer! The latest C++ standard is officially finalized, and it’s packed with features that make the language safer and more powerful. If you’ve been waiting for less boilerplate and better performance, this is for you. Key highlights include: 🔹 Static Reflection: Finally, the ability to inspect types at compile-time! 🔹 Contract Programming: Built-in preconditions and postconditions for safer code. 🔹 Linear Algebra Library: Native support for high-performance math. 🔹 #embed: A much simpler way to include binary data in your projects. C++ continues to evolve, proving it’s still the backbone of high-performance software. Check out the full list of features here: cppreference.com #Cpp26 #Programming #SoftwareDevelopment #Coding #CPP #TechUpdates https://lnkd.in/gbe6RqHh
To view or add a comment, sign in
-
Mutex might sound like the solution here, but you also essentially lose the parallelism by making the thread wait for other threads to finish work. Things LIKE atomics should be considered the defacto answer, mutexes are a last resort.
Debugging a Race Condition in C++ While working on a multithreaded module, I encountered an unexpected issue. Even though the logic looked correct, the final output was inconsistent every time. Problem: Multiple threads were updating a shared variable without synchronization. Expected: 200000 Actual: Random incorrect values After debugging, I found the root cause: Race Condition due to non-atomic operation (counter++) Key Learning: In multithreading, even a simple increment operation is not safe. It involves: Read → Modify → Write When multiple threads execute this simultaneously, data gets corrupted. Solution: Used mutex to synchronize access to shared resource. Also improved code using: lock_guard<mutex> for better safety and readability. Takeaway: Never trust shared data in multithreaded environments without proper synchronization. #cpp #multithreading #racecondition #concurrency #debugging
To view or add a comment, sign in
-
-
One of the most common performance mistakes in C#: Using += for string concatenation in loops. Why it matters: Strings are immutable Each operation creates a new object Memory usage grows rapidly Solution: StringBuilder Simple fix. Huge impact. #csharp #dotnet #cleancode #performance
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
It’s good to people using smart pointers. However, we need to enforce that using raw pointers is almost never a nice idea, until we are working on low level data structures. And as Sean says, smart pointers are also raw pointers.