<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Peter Michell on Medium]]></title>
        <description><![CDATA[Stories by Peter Michell on Medium]]></description>
        <link>https://medium.com/@petercovingtonmitchell?source=rss-b24c609bba7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dAgq4H82qlxe3_HyXLNkRA.png</url>
            <title>Stories by Peter Michell on Medium</title>
            <link>https://medium.com/@petercovingtonmitchell?source=rss-b24c609bba7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:46:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@petercovingtonmitchell/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a HIPAA-Compliant FHIR API with FastAPI: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@petercovingtonmitchell/building-a-hipaa-compliant-fhir-api-with-fastapi-a-step-by-step-guide-f6d2897383ee?source=rss-b24c609bba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6d2897383ee</guid>
            <dc:creator><![CDATA[Peter Michell]]></dc:creator>
            <pubDate>Fri, 20 Jun 2025 04:50:42 GMT</pubDate>
            <atom:updated>2025-06-20T04:50:42.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zo_mF1qGh2WySH2bqjj4Gw.png" /></figure><p>As healthcare data silos continue to fragment patient care, interoperability has never been more critical. The FHIR (Fast Healthcare Interoperability Resources) standard is rapidly becoming the go-to spec for exchanging clinical information across systems — and FastAPI gives us a lightweight, high-performance way to expose FHIR resources securely and at scale.</p><p>In this walkthrough, you’ll build a HIPAA-compliant FHIR server from scratch, covering:</p><ul><li><strong>FHIR Resource Modeling</strong>: Define Patient, Observation, and Medication resources using Pydantic and the fhir.resources library.</li><li><strong>Secure Endpoints</strong>: Expose and protect RESTful routes with OAuth2 scopes and JWT-based authentication.</li><li><strong>Audit &amp; Logging</strong>: Implement request/response logging (with PHI redaction) for compliance and traceability.</li><li><strong>Data Persistence</strong>: Store raw FHIR JSON in SQL Server via SQLAlchemy, with clean ETL patterns.</li><li><strong>Production Deployment</strong>: Run behind TLS (or through API Gateway) to meet real-world security and uptime requirements.</li></ul><h3>Project Setup</h3><p>First, create a fresh virtual environment and install our dependencies:</p><pre>mkdir fhir-fastapi<br>cd fhir-fastapi<br>python3 -m venv venv<br>source venv/bin/activate<br>pip install fastapi uvicorn sqlalchemy pydantic fhir.resources python-jose</pre><ul><li><strong>FastAPI &amp; Uvicorn</strong> power our web server</li><li><strong>SQLAlchemy</strong> handles DB interactions</li><li><strong>Pydantic</strong> and <strong>fhir.resources</strong> give us FHIR-compliant models</li><li><strong>python-jose</strong> provides JWT-based auth</li></ul><p>You’re now ready to start coding your first FHIR resource!</p><h3><strong>Defining a FHIR Patient Model</strong></h3><p>Create a Pydantic model that mirrors the FHIR “Patient” resource. We’ll use the fhir.resources library under the hood to validate against the official spec:</p><pre># models/patient.py<br>from pydantic import BaseModel, Field<br>from fhir.resources.patient import Patient as FHIRPatient<br><br>class PatientIn(BaseModel):<br>    resourceType: str = Field(&quot;Patient&quot;, const=True)<br>    id: str<br>    name: list<br>    gender: str<br>    birthDate: str<br><br>    def to_fhir(self) -&gt; FHIRPatient:<br>        return FHIRPatient.parse_obj(self.dict())</pre><ul><li>resourceType is fixed to &quot;Patient&quot;</li><li>Arbitrary JSON fields (name, gender, birthDate) follow the FHIR schema</li><li>.to_fhir() returns a fully‐validated FHIRPatient object ready for storage or serialization</li></ul><h3>Secure Endpoints &amp; OAuth2 Protection</h3><p>Expose RESTful endpoints and lock them down with OAuth2 scopes. Here’s how to issue tokens and guard our /Patientroute:</p><pre># main.py (excerpt)<br>from fastapi import FastAPI, Depends, HTTPException, status<br>from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm<br>from jose import JWTError, jwt<br>from sqlalchemy.orm import Session<br>from db import get_db<br>from models.patient import PatientIn<br><br>app = FastAPI(title=&quot;FHIR FastAPI Demo&quot;)<br>oauth2_scheme = OAuth2PasswordBearer(tokenUrl=&quot;token&quot;)<br><br>SECRET = &quot;CHANGE_THIS_SECRET&quot;<br>ALGORITHM = &quot;HS256&quot;<br><br>def verify_token(token: str = Depends(oauth2_scheme)):<br>    try:<br>        payload = jwt.decode(token, SECRET, algorithms=[ALGORITHM])<br>        if payload.get(&quot;scope&quot;) != &quot;fhir.read&quot;:<br>            raise HTTPException(403, &quot;Insufficient scope&quot;)<br>    except JWTError:<br>        raise HTTPException(401, &quot;Invalid token&quot;)<br><br>@app.post(&quot;/token&quot;)<br>def login(form: OAuth2PasswordRequestForm = Depends()):<br>    if form.username == &quot;provider&quot; and form.password == &quot;secure&quot;:<br>        token = jwt.encode({&quot;sub&quot;: form.username, &quot;scope&quot;: &quot;fhir.read&quot;}, SECRET, algorithm=ALGORITHM)<br>        return {&quot;access_token&quot;: token, &quot;token_type&quot;: &quot;bearer&quot;}<br>    raise HTTPException(400, &quot;Incorrect credentials&quot;)<br><br>@app.post(&quot;/Patient&quot;, dependencies=[Depends(verify_token)], status_code=201)<br>def create_patient(payload: PatientIn, db: Session = Depends(get_db)):<br>    fhir_obj = payload.to_fhir()<br>    # Assume db_session has an add_patient method<br>    created = db.add_patient(fhir_obj)  <br>    return {&quot;id&quot;: created.id}</pre><ul><li><strong>/token</strong> issues scoped JWTs for clients</li><li><strong>verify_token</strong> enforces the fhir.read scope before granting access</li><li><strong>create_patient</strong> ingests a FHIR-validated payload</li></ul><h3><strong>SQL Server Persistence</strong></h3><p>Leverage SQLAlchemy to store raw FHIR JSON in a SQL Server table. This keeps your schema flexible:</p><pre># db.py<br>from sqlalchemy import create_engine, Column, String, Table, MetaData<br>from sqlalchemy.orm import sessionmaker<br><br>DATABASE_URL = &quot;mssql+pyodbc://user:pass@server/HealthcareDB?driver=ODBC+Driver+17+for+SQL+Server&quot;<br>engine = create_engine(DATABASE_URL)<br>SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)<br>metadata = MetaData()<br><br>PatientTable = Table(<br>    &quot;patients&quot;, metadata,<br>    Column(&quot;id&quot;, String, primary_key=True),<br>    Column(&quot;raw_json&quot;, String),<br>)<br><br>def init_db():<br>    metadata.create_all(engine)<br><br>def get_db():<br>    db = SessionLocal()<br>    try:<br>        yield db<br>    finally:<br>        db.close()<br><br>def add_patient(self, fhir_patient):<br>    ins = PatientTable.insert().values(<br>        id=fhir_patient.id, <br>        raw_json=fhir_patient.json()<br>    )<br>    self.execute(ins)<br>    self.commit()<br>    return fhir_patient</pre><ul><li>Stores entire FHIR resource as JSON for full fidelity</li><li>Easily extends to other resource types without altering schema</li></ul><h3><strong>Deployment &amp; TLS</strong></h3><p>For HIPAA compliance and production readiness, run Uvicorn behind TLS:</p><pre>uvicorn main:app \<br>  --host 0.0.0.0 --port 443 \<br>  --ssl-keyfile=/etc/ssl/private/server.key \<br>  --ssl-certfile=/etc/ssl/certs/server.crt</pre><p><strong>Extras for real-world use:</strong></p><ul><li>Place NGINX or AWS API Gateway in front for rate limiting, request buffering, and DDoS protection.</li><li>Integrate Python’s logging module to audit all FHIR calls—masking PHI in logs for compliance.</li><li>Automate certificate renewal with Let’s Encrypt for zero-downtime TLS updates.</li></ul><h3>Conclusion</h3><p>You now have a blueprint for a secure, scalable, and standards-compliant FHIR API using FastAPI. This template can be extended to any FHIR resource — Observation, Medication, Encounter — and adapted to your organization’s existing EHR systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6d2897383ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Suspense in React: Elevating Your Application’s Performance]]></title>
            <link>https://medium.com/@petercovingtonmitchell/the-art-of-suspense-in-react-elevating-your-applications-performance-bfe04f3fe5e4?source=rss-b24c609bba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfe04f3fe5e4</guid>
            <dc:creator><![CDATA[Peter Michell]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 17:02:41 GMT</pubDate>
            <atom:updated>2024-04-17T17:02:41.681Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering React Suspense: Streamlining Asynchronous Operations for Enhanced User Experience</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMUAfrHInWGo6p_QSrEVAw.png" /></figure><p>React<strong> Suspense</strong>, unveiled in React 16.6, revolutionizes asynchronous data handling by seamlessly pausing component rendering during data retrieval. It empowers developers to manage loading states effortlessly, presenting fallback content during processes like data fetching, image loading, or code splitting.</p><p>React Suspense improves the user experience by providing a smoother transition from a loading state to a fully rendered component. Instead of showing a blank screen or a loading spinner while waiting for data, you can use Suspense to display a fallback component or some other placeholder content.</p><h3>Why Integrate Suspense Features</h3><ul><li><strong>Asynchronous Data Fetching</strong>: Suspense allows components to wait for something before they can render, which is particularly useful for handling asynchronous data fetching.</li><li><strong>Loading State Handling</strong>: Suspense provides a more declarative way to specify loading states in your components, making your code easier to read and maintain.</li><li><strong>Code Splitting</strong>: Suspense can be used with React.lazy to easily implement code splitting, which can significantly reduce the initial load time of your app.</li><li><strong>Better User Experience</strong>: By allowing you to easily specify fallback loading states, Suspense can help prevent jarring transitions and improve the overall user experience.</li><li><strong>Error Boundaries</strong>: Suspense works seamlessly with error boundaries, making it easier to handle errors that occur during rendering.</li><li><strong>Integrated with Concurrent Mode</strong>: When used with React’s Concurrent Mode, Suspense allows you to keep your app responsive while rendering large component trees and fetching data.</li></ul><h3>Suspense By Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*RdwIwaceQPcs0hDczqx5EA.png" /></figure><ol><li>It displays a list of buttons, each representing a blog post. When a button is clicked, it sets the ID of the post to be displayed.</li><li>When the post ID changes, the application fetches the data for the new post and its comments. This is simulated with promises that resolve after a delay.</li><li>While the data is being fetched, the application displays loading indicators. This is handled by the Suspense components, which catch the promises thrown by the read method of the resources.</li><li>If the post ID is greater than 5, the fetchPost function throws an error. This is caught by the ErrorBoundary component, which displays an error message.</li><li>Once the data is available, the application displays the post and its comments. If the data is not yet available when the Post or Comments component tries to render, the read method of the resource throws the promise, which triggers the Suspense fallback.</li></ol><pre> <br>// Define a function that fetches some data<br>const fetchPost = (id) =&gt;<br>  new Promise((resolve, reject) =&gt;<br>    setTimeout(() =&gt; {<br>      if (id &gt; 5) {<br>        reject(new Error(&quot;Invalid post ID&quot;));<br>      } else {<br>        resolve({<br>          id,<br>          title: `Post ${id}`,<br>          content: `This is the content of post ${id}`,<br>        });<br>      }<br>    }, 2000 * id),<br>  );<br><br>// Define a function that fetches comments for a post<br>const fetchComments = (postId) =&gt;<br>  new Promise((resolve) =&gt;<br>    setTimeout(() =&gt; {<br>      resolve(<br>        Array.from({ length: 5 }, (_, i) =&gt; ({<br>          id: i,<br>          content: `Comment ${i} on post ${postId}`,<br>        })),<br>      );<br>    }, 2000 * postId),<br>  );<br><br>// Create a resource with a read() method that throws the promise if data is not yet available<br>const createResource = (promise) =&gt; {<br>  let status = &quot;loading&quot;;<br>  let result;<br>  let error;<br>  return {<br>    read() {<br>      if (status === &quot;loading&quot;) {<br>        throw promise.then(<br>          (r) =&gt; {<br>            status = &quot;success&quot;;<br>            result = r;<br>          },<br>          (e) =&gt; {<br>            status = &quot;error&quot;;<br>            error = e;<br>          },<br>        );<br>      } else if (status === &quot;success&quot;) {<br>        return result;<br>      } else if (status === &quot;error&quot;) {<br>        throw error;<br>      }<br>    },<br>  };<br>};<br><br>// Wrap our component with Suspense and ErrorBoundary to handle data fetching<br>const App = () =&gt; {<br>  const [id, setId] = useState(1);<br>  const [postResource, setPostResource] = useState(<br>    createResource(fetchPost(id)),<br>  );<br>  const [commentsResource, setCommentsResource] = useState(<br>    createResource(fetchComments(id)),<br>  );<br>  const prevId = useRef(id);<br><br>  useEffect(() =&gt; {<br>    if (prevId.current !== id) {<br>      setPostResource(createResource(fetchPost(id)));<br>      setCommentsResource(createResource(fetchComments(id)));<br>      prevId.current = id;<br>    }<br>  }, [id]);<br><br>  return (<br>    &lt;div className=&quot;container&quot;&gt;<br>      &lt;h1 className=&quot;title&quot;&gt;Posts&lt;/h1&gt;<br>      &lt;div&gt;<br>        {Array.from({ length: 6 }, (_, i) =&gt; i + 1).map((postId) =&gt; (<br>          &lt;button className=&quot;button&quot; key={postId} onClick={() =&gt; setId(postId)}&gt;<br>            View Post {postId}<br>          &lt;/button&gt;<br>        ))}<br>      &lt;/div&gt;<br>      &lt;ErrorBoundary&gt;<br>        &lt;Suspense fallback={&lt;div className=&quot;loader&quot;&gt;Loading post...&lt;/div&gt;}&gt;<br>          &lt;Post resource={postResource} /&gt;<br>        &lt;/Suspense&gt;<br>        &lt;Suspense fallback={&lt;div className=&quot;loader&quot;&gt;Loading comments...&lt;/div&gt;}&gt;<br>          &lt;Comments resource={commentsResource} /&gt;<br>        &lt;/Suspense&gt;<br>      &lt;/ErrorBoundary&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*j5LyBSTUa0x93cJa4jhWGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*0OnA7BQwrMcS1fesoCxR_g.png" /></figure><h3>What we are achieving and why it matters</h3><p><strong>Declarative Data Fetching</strong>: React Suspense shifts the paradigm of data fetching <em>from imperative to declarative</em>. Instead of manually handling loading states and error conditions, Suspense allows developers to declare what data is needed and let&#39;s React handle the rest. In our example, the &lt;Suspense&gt; component wraps the &lt;Post&gt; and &lt;Comments&gt; components, <em>signaling React to wait for data before rendering</em>. This declarative approach streamlines the codebase, enhancing readability and maintainability.</p><pre>&lt;Suspense fallback={&lt;div className=&quot;loader&quot;&gt;Loading post...&lt;/div&gt;}&gt;<br>  &lt;Post resource={postResource} /&gt;<br>&lt;/Suspense&gt;<br>&lt;Suspense fallback={&lt;div className=&quot;loader&quot;&gt;Loading comments...&lt;/div&gt;}&gt;<br>  &lt;Comments resource={commentsResource} /&gt;<br>&lt;/Suspense&gt;</pre><p><strong>Granular Loading States:</strong> One of the standout features of Suspense is its ability to specify loading fallbacks at the component level. In our example, each &lt;Suspense&gt; component defines its loading indicator (&lt;div className=”loader”&gt;Loading post…&lt;/div&gt; and &lt;div className=”loader”&gt;Loading comments…&lt;/div&gt;).</p><p>“This granular control enables developers to <em>craft tailored loading experiences for different parts</em> of the UI, ensuring a cohesive and polished user interface.”</p><pre>&lt;Suspense fallback={&lt;div className=&quot;loader&quot;&gt;Loading post...&lt;/div&gt;}&gt;<br>  {/* Post component */}<br>&lt;/Suspense&gt;<br>&lt;Suspense fallback={&lt;div className=&quot;loader&quot;&gt;Loading comments...&lt;/div&gt;}&gt;<br>  {/* Comments component */}<br>&lt;/Suspense&gt;</pre><p><strong>Error Handling with Grace:</strong> React Suspense seamlessly integrates with Error Boundaries to gracefully handle errors during data fetching. By encapsulating potential errors within the &lt;ErrorBoundary&gt; component, our example ensures that <em>any fetch failures are caught and elegantly</em> <em>displayed to the user </em>(&lt;div&gt;Error: {this.state.error.message}&lt;/div&gt;).</p><p>“This fault-tolerant approach <em>prevents application crashes and enhances user trust </em>by maintaining a smooth user experience under adverse conditions.”</p><pre>class ErrorBoundary extends Component {<br>  state = { error: null };<br><br>  static getDerivedStateFromError(error) {<br>    return { error };<br>  }<br><br>  render() {<br>    if (this.state.error) {<br>      return &lt;div&gt;Error: {this.state.error.message}&lt;/div&gt;;<br>    }<br><br>    return this.props.children;<br>  }<br>}</pre><p><strong>Simplified Resource Management</strong>: Suspense simplifies resource management by encapsulating data fetching logic within resources. In our example, the <em>createResource function</em> abstracts away the complexity of managing asynchronous operations, allowing developers to focus on building features rather than wrangling with data fetching intricacies.</p><p>“This abstraction promotes <em>code reusability and maintainability</em>, fostering a more efficient development process.”</p><pre>const createResource = (promise) =&gt; {<br>  let status = &quot;loading&quot;;<br>  let result;<br>  let error;<br>  return {<br>    read() {<br>      if (status === &quot;loading&quot;) {<br>        throw promise.then(<br>          (r) =&gt; {<br>            status = &quot;success&quot;;<br>            result = r;<br>          },<br>          (e) =&gt; {<br>            status = &quot;error&quot;;<br>            error = e;<br>          },<br>        );<br>      } else if (status === &quot;success&quot;) {<br>        return result;<br>      } else if (status === &quot;error&quot;) {<br>        throw error;<br>      }<br>    },<br>  };<br>};</pre><h3><strong>Conclusion: Embracing React Suspense for Modern Development</strong></h3><p>React Suspense emerges as a cornerstone in contemporary web development, offering an array of features that streamline data handling and elevate user experience. Its <strong>declarative approach</strong>, <strong>granular loading states</strong>, and <strong>seamless error handling</strong> redefine how developers manage asynchronous operations.</p><p>By harnessing the power of Suspense, developers can craft resilient, performant applications with ease. It <strong>simplifies resource management</strong>, <strong>optimizes performance</strong>, and <strong>enhances user satisfaction</strong>, paving the way for a more intuitive and efficient development process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfe04f3fe5e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elevating Memory Management: Harnessing the Power of Smart Pointers in C++]]></title>
            <link>https://medium.com/@petercovingtonmitchell/elevating-memory-management-harnessing-the-power-of-smart-pointers-in-c-dc9ef288fc68?source=rss-b24c609bba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc9ef288fc68</guid>
            <dc:creator><![CDATA[Peter Michell]]></dc:creator>
            <pubDate>Fri, 08 Mar 2024 22:29:58 GMT</pubDate>
            <atom:updated>2024-03-08T22:29:58.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hF4L9_a3DKR2iDyb68ksJQ.jpeg" /></figure><p><em>Smart pointers aren’t just an upgrade — they’re a game-changer in memory management. With their enhanced safety and efficiency, they revolutionize how we handle memory compared to raw pointers. By slashing the risk of memory-related bugs, they take code readability and maintainability to a whole new level.</em></p><h3>An Overview of Smart Pointer Varieties</h3><p>1.std::unique_ptr: This is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of using the associated deleter of the unique_ptr. A unique_ptr cannot be copied to another unique_ptr, passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. This ensures that the unique_ptr maintains ownership of its managed object.</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>class MyClass {<br>public:<br>    MyClass() { std::cout &lt;&lt; &quot;MyClass constructed\n&quot;; } // Message when MyClass is constructed<br>    ~MyClass() { std::cout &lt;&lt; &quot;MyClass destroyed\n&quot;; } // Message when MyClass is destroyed<br>    void classMethod() { std::cout &lt;&lt; &quot;MyClass method called\n&quot;; } // A simple method in MyClass<br>};<br><br>int main() {<br>    // A std::unique_ptr is used to manage a MyClass object.<br>    std::unique_ptr&lt;MyClass&gt; ptr = std::make_unique&lt;MyClass&gt;();<br><br>    ptr-&gt;classMethod(); // Call method on MyClass<br><br>    // The unique_ptr automatically deletes the MyClass instance when it goes out of scope.<br>    // This is when the main function ends.<br>    // This is demonstrated by the &quot;MyClass destroyed&quot; message that is printed when the program ends.<br>    // The std::unique_ptr ensures that the MyClass object is properly cleaned up, preventing memory leaks.<br><br>    return 0;<br>}</pre><p>2.std::shared_ptr: This is a smart pointer that retains shared ownership of an object through a pointer. Several shared_ptr objects may own the same object. The object is destroyed and its memory deallocated when either of the following happens:</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>class MyClass {<br>public:<br>    MyClass() { std::cout &lt;&lt; &quot;MyClass constructed\n&quot;; }<br>    ~MyClass() { std::cout &lt;&lt; &quot;MyClass destroyed\n&quot;; }<br>    void classMethod() { std::cout &lt;&lt; &quot;MyClass method called\n&quot;; }<br>};<br><br>int main() {<br>    // A std::shared_ptr is used to manage a MyClass object.<br>    std::shared_ptr&lt;MyClass&gt; ptr1 = std::make_shared&lt;MyClass&gt;();<br>    ptr1-&gt;classMethod();<br><br>    {<br>        // Another shared_ptr, ptr2, also points to the same MyClass object.<br>        // This demonstrates the shared ownership feature of std::shared_ptr.<br>        std::shared_ptr&lt;MyClass&gt; ptr2 = ptr1;<br>        ptr2-&gt;classMethod();<br>    } // ptr2 goes out of scope here and is destroyed, but the MyClass object is not destroyed because ptr1 is still pointing to it.<br><br>    ptr1-&gt;classMethod();<br><br>    // The MyClass object is automatically destroyed when the last shared_ptr pointing to it (ptr1) goes out of scope.<br>    // This is demonstrated by the &quot;MyClass destroyed&quot; message that is printed when the program ends.<br>    // The std::shared_ptr ensures that the MyClass object is properly cleaned up, preventing memory leaks.<br><br>    return 0;<br>}</pre><p>3.std::weak_ptr: This is a smart pointer that holds a non-owning (&quot;weak&quot;) reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object. std::weak_ptr models temporary ownership: when an object needs to be accessed only if it exists, and it may be deleted at any time by someone else, std::weak_ptr is used to track the object. std::weak_ptr is used in conjunction with std::shared_ptr to model the &quot;observer&quot; design pattern. It&#39;s a level of indirection and control over the object&#39;s lifetime.</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>class MyClass {<br>public:<br>    MyClass { std::cout &lt;&lt; &quot;MyClass constructed\n&quot;; }<br>    ~MyClass() { std::cout &lt;&lt; &quot;MyClass destroyed\n&quot;; }<br>    void classMethod() { std::cout &lt;&lt; &quot;MyClass method called\n&quot;; }<br>};<br><br>int main() {<br>    // A std::shared_ptr is used to manage a MyClass object.<br>    std::shared_ptr&lt;MyClass&gt; ptr1 = std::make_shared&lt;MyClass&gt;();<br>    ptr1-&gt;classMethod();<br><br>    // A std::weak_ptr is used to hold a non-owning reference to the MyClass object.<br>    std::weak_ptr&lt;MyClass&gt; weak1 = ptr1;<br><br>    {<br>        // Another shared_ptr, ptr2, also points to the same MyClass object.<br>        // This demonstrates the shared ownership feature of std::shared_ptr.<br>        std::shared_ptr&lt;MyClass&gt; ptr2 = ptr1;<br>        ptr2-&gt;classMethod();<br><br>        // Check if the object still exists using the weak_ptr.<br>        if (auto spt = weak1.lock()) { // Has to be copied into a shared_ptr before usage<br>            std::cout &lt;&lt; &quot;Object still exists!\n&quot;;<br>        } else {<br>            std::cout &lt;&lt; &quot;Object has been deleted!\n&quot;;<br>        }<br>    } // ptr2 goes out of scope here and is destroyed, but the MyClass object is not destroyed because ptr1 is still pointing to it.<br><br>    ptr1-&gt;classMethod();<br><br>    // The MyClass object is automatically destroyed when the last shared_ptr pointing to it (ptr1) goes out of scope.<br>    // This is demonstrated by the &quot;MyClass destroyed&quot; message that is printed when the program ends.<br>    // The std::shared_ptr ensures that the MyClass object is properly cleaned up, preventing memory leaks.<br><br>    return 0;<br>}</pre><h3>Key Advantages In Memory Use</h3><ol><li>std::unique_ptr: This smart pointer provides exclusive ownership of the memory it manages. <strong>It automatically deletes the object it points to when the</strong> unique_ptr<strong> goes out of scope.</strong> This helps prevent memory leaks and is useful when a resource is only needed during the lifetime of a specific scope.</li><li>std::shared_ptr: This smart pointer <strong>allows multiple pointers to own the same resource.</strong> This is useful when you want to share a resource among multiple owners and don&#39;t want the resource to be deleted until all owners are done with it. <strong>The resource is automatically deleted when the last </strong>shared_ptr<strong> pointing to it is destroyed or reset.</strong></li><li>std::weak_ptr: This smart pointer <strong>holds a non-owning reference to an object that is managed by </strong>std::shared_ptr. It&#39;s used to break circular references between shared_ptr instances. A weak_ptr can be promoted to a shared_ptr to access the object. <strong>The object will not be deleted as long as there&#39;s a </strong>shared_ptr<strong> or </strong>weak_ptr<strong> referencing it.</strong></li></ol><h3>Overview of Related Memory Enhancements</h3><ol><li><strong>Custom Deleters</strong>: All three smart pointers allow for custom deleters. This means you can specify a custom function or functor that is called to delete the managed object. This is useful when dealing with resources other than memory, like file handles or network connections.</li><li><strong>Memory Overhead</strong>: std::shared_ptr has more memory overhead than std::unique_ptr because it needs to keep track of the reference count. This is something to consider when memory usage is a concern.</li><li><strong>Thread Safety</strong>: std::shared_ptr is thread-safe in the sense that you can safely use different shared_ptr objects in multiple threads simultaneously, even when these objects share the same managed object. However, you&#39;ll still need to synchronize access to the shared object itself.</li><li><strong>Avoiding Circular References</strong>: std::weak_ptr is useful for avoiding circular references, which can lead to memory leaks with std::shared_ptr. A circular reference occurs when two or more shared_ptr objects refer to each other directly or indirectly, causing the reference count to never reach zero and the memory to never be freed.</li><li><strong>Nullptr Comparisons</strong>: All three smart pointers can be compared to nullptr to check if they own an object.</li><li><strong>Move Semantics</strong>: std::unique_ptr supports move semantics but not copy semantics. This makes it useful for objects that should not be copied, like file handles or sockets.</li><li><strong>Resource Acquisition Is Initialization (RAII)</strong>: All three smart pointers are implementations of the RAII idiom. This means they tie the lifetime of the resource they manage to the lifetime of the object, which is determined by the scope in which the object is created. This helps ensure resources are properly cleaned up and makes code easier to understand.</li></ol><h3>Don’t Fear Memory Management in C++: Embrace Smart Pointers</h3><p>C++ often gets a bad rap due to its complexity and the difficulty of managing memory safely. However, with the introduction of smart pointers like std::unique_ptr, std::shared_ptr, and std::weak_ptr, memory management in C++ has become much safer and more straightforward. These smart pointers automatically manage the lifetime of objects, preventing common issues like memory leaks and dangling pointers. They embody the principle of RAII (Resource Acquisition Is Initialization), tying the lifetime of a resource to the lifetime of an object.</p><p>Moreover, smart pointers provide additional features like custom deleters, shared ownership, and weak references, which offer more control over how and when objects are deleted. They also support move semantics, which can improve performance by eliminating unnecessary copies.</p><p>Despite its challenges, C++ is known for its efficiency and performance. By using smart pointers, developers can write safer and more robust code without sacrificing the speed and power that C++ offers. This makes C++ a great choice for high-performance applications that also require careful resource management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc9ef288fc68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>