DEV Community

Cover image for ๐Ÿงฌ I Built Memory That Dies If You Don't Use It (And You Should Too)
Alexandru Rusu
Alexandru Rusu

Posted on

๐Ÿงฌ I Built Memory That Dies If You Don't Use It (And You Should Too)

*# ๐Ÿงฌ I Built Memory That Dies If You Don't Use It (And You Should Too)
*

What if your variables had expiration dates? What if they rotted away when you forgot about them? Welcome to LibOrganic โ€” biodegradable memory for C++.


The Problem With Immortal Variables

You know that feeling when you're debugging at 3 AM and you find a variable that's been holding a stale value for the last 47 function calls? Or when you're building a game and your player's health never drains because you forgot to update it?

Traditional variables are immortal. They hold their value forever, until you explicitly change them. They don't care if you've touched them in the last hour, day, or year. They just... sit there.

But what if variables could decay? What if they had a time-to-live and started corrupting themselves when you neglected them?

That's exactly what I built: LibOrganic โ€” a C++20 library that makes your memory mortal.


๐ŸŽฏ The Concept

LibOrganic wraps any type T in an Organic<T> container that:

  • โฑ๏ธ Has a time-to-live (TTL) in milliseconds
  • ๐Ÿฆ  Decays when you don't access it for too long
  • ๐Ÿ”„ Resets its timer when you touch it (via get())
  • ๐ŸŽจ Uses pluggable corruption strategies (drift, bit-flip, nullify, regen)
  • โธ๏ธ Can be paused/resumed on demand

Think of it like:

  • ๐Ÿฅ› Milk that spoils if you don't drink it
  • ๐Ÿ”‹ Batteries that drain when idle
  • ๐Ÿง  Memories that fade without recall

๐Ÿ’ป How It Works

Basic Usage

#include "Organic.h"

int main() {
    // Create a variable with 2 second lifetime
    auto health = Organic<int>::create(100, 2000);

    std::cout << health->get();  // 100 โ€” access resets timer

    // Wait 3 seconds (not accessing it)
    std::this_thread::sleep_for(3s);

    std::cout << health->peek(); // 89 โ€” it decayed! ๐Ÿฆ 

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

The Magic Behind It

Under the hood, LibOrganic uses:

  1. DecayManager โ€” A singleton with a background thread (std::jthread) that checks every second if any Organic objects have expired
  2. Strategy Pattern โ€” Pluggable corruption algorithms:

    • DriftStrategy โ€” Gradually shifts values (ยฑ10%)
    • BitFlipStrategy โ€” Random bit corruption (chaos mode)
    • NullifyStrategy โ€” Resets to zero/default
    • RegenStrategy โ€” Increases value up to max (perfect for stamina/mana)
  3. Smart Pointers โ€” Uses weak_ptr to avoid circular dependencies and auto-cleanup

Architecture

User Code
    โ†“
Organic<T> (wraps your value + tracks last access)
    โ†“ (registers via weak_ptr)
DecayManager (background thread checks every 1s)
    โ†“ (calls decay() if expired)
CorruptionStrategy (modifies the value)
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฎ Real-World Use Cases

1. Game Development

// Health that drains when idle
auto playerHealth = Organic<int>::create(100, 5000);
playerHealth->setStrategy(std::make_unique<DriftStrategy<int>>());

// Stamina that regenerates
auto stamina = Organic<int>::create(30, 2000);
stamina->setStrategy(std::make_unique<RegenStrategy<int>>(100, 0.2));
Enter fullscreen mode Exit fullscreen mode

2. Security โ€” Auto-Expiring Keys

// Encryption key that nullifies after 5 minutes
auto secretKey = Organic<std::string>::create("super-secret-key", 300000);
secretKey->setStrategy(std::make_unique<NullifyStrategy<std::string>>());

secretKey->onDecay([](const std::string& old, const std::string& now) {
    std::cout << "โš ๏ธ Key expired! Clearing memory...\n";
});
Enter fullscreen mode Exit fullscreen mode

3. Testing โ€” Memory Corruption Simulation

// Simulate bit-flip errors
auto testData = Organic<uint32_t>::create(0xDEADBEEF, 1000);
testData->setStrategy(std::make_unique<BitFlipStrategy<uint32_t>>());

// Perfect for testing error handling!
Enter fullscreen mode Exit fullscreen mode

4. Self-Invalidating Cache

// Cache entry that decays after 10 seconds
auto cachedResult = Organic<MyData>::create(computeExpensive(), 10000);
// If you don't access it, it corrupts and forces recomputation
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ Advanced Features

Callbacks

auto mana = Organic<int>::create(50, 1500);
mana->onDecay([](const int& old, const int& now) {
    std::cout << "Mana changed: " << old << " -> " << now << "\n";
    if (now < 10) {
        playLowManaSound();
    }
});
Enter fullscreen mode Exit fullscreen mode

Pause/Resume

mana->pause();  // Freeze decay
// ... do something that takes time ...
mana->resume(); // Unfreeze (timer resets)
Enter fullscreen mode Exit fullscreen mode

Peek vs Get

auto value = health->get();   // Reads AND resets timer
auto value = health->peek();  // Reads WITHOUT resetting timer
health->touch();              // Resets timer WITHOUT reading
Enter fullscreen mode Exit fullscreen mode

๐Ÿงช Why I Built This

I was working on a game prototype and wanted health/stamina systems that felt more "organic" โ€” values that naturally degraded over time unless you actively maintained them. I also wanted to experiment with C++20 features like std::jthread and modern memory management patterns.

The result? A library that's:

  • โœ… Header-only (easy to integrate)
  • โœ… Lock-free (uses atomics for performance)
  • โœ… Type-safe (templates, baby!)
  • โœ… Extensible (add your own strategies)

๐Ÿ“ฆ Installation

Header-Only (Recommended)

Just copy the include/ folder:

#include "liborganic/Organic.h"
Enter fullscreen mode Exit fullscreen mode

Build from Source

git clone https://github.com/alexandrusu1/LibOrganic.git
cd LibOrganic
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
cmake --build . --parallel
Enter fullscreen mode Exit fullscreen mode

๐Ÿค” Is This Actually Useful?

Honestly? It depends.

For production code? Probably not. You want predictable, deterministic behavior.

But for:

  • ๐ŸŽฎ Game prototypes โ€” Absolutely! Makes mechanics feel more alive
  • ๐Ÿงช Testing โ€” Great for simulating corruption/errors
  • ๐ŸŽ“ Learning โ€” Excellent C++20 practice
  • ๐ŸŽจ Art projects โ€” Why not? Code can be art too

Sometimes the best projects are the ones that make you think: "Wait, why hasn't anyone done this before?"


๐ŸŽฏ What's Next?

Ideas for future updates:

  • [ ] Configurable decay curves (linear, exponential, step functions)
  • [ ] Thread-safe value access with mutex
  • [ ] Serialization support
  • [ ] Python bindings (because why not?)
  • [ ] Gaussian noise strategy
  • [ ] Byte shuffle strategy

๐Ÿ’ฌ Your Turn

Have you ever wanted variables that decay? What would you use this for? Drop a comment below or check out the GitHub repo!

Remember: In LibOrganic, all memory is mortal. ๐Ÿงฌ


Built with ๐Ÿงฌ and C++20

Top comments (2)

Collapse
 
sloan profile image
Sloan the DEV Moderator

We loved your post so we shared it on social.

Keep up the great work!

Collapse
 
pgradot profile image
Pierre Gradot

Remember: In LibOrganic, all memory is mortal

Does this mean that the singleton thread is organic too? :o