Cursor rules for modern C++ ownership following the Core Guidelines, with unique_ptr by default, non-owning raw pointers, span, and sanitizer checks.
.cursor/rules/c-memory-management-modern.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for modern C++ ownership following the Core Guidelines, with unique_ptr by default, non-owning raw pointers, span, and sanitizer checks."
globs: "**/*"
alwaysApply: false
---
# Modern C++ Memory Management
Applies to: C++ source and headers (`**/*.cpp`, `**/*.cc`, `**/*.h`, `**/*.hpp`) that allocate, own or reference objects.
Version baseline: checked against the C++ Core Guidelines and C++20 (`std::span` needs C++20; `std::make_unique` needs C++14). Read the build files (`CMakeLists.txt`, `CMAKE_CXX_STANDARD`, compiler flags) and follow the standard the project compiles with.
## Ownership rules
1. Every resource has exactly one clear owner, expressed in the type: a value, a container, `std::unique_ptr`, or (when ownership is really shared) `std::shared_ptr`.
2. No naked `new`/`delete` in application code. Create with `std::make_unique` / `std::make_shared`; prefer plain values and containers when no heap identity is needed.
3. A raw pointer `T*` or reference `T&` means "non-owning". Use them freely for parameters and observers whose lifetime is guaranteed by the caller.
4. Default to `std::unique_ptr`; use `std::shared_ptr` only when several owners must keep the object alive and no single owner can be named.
5. Use `std::weak_ptr` to observe a `shared_ptr`-managed object that may be destroyed while you hold the observer, and to break `shared_ptr` cycles. It is not a general-purpose observer pointer.
6. Wrap every other resource (files, sockets, locks, OS handles) in an RAII type whose destructor releases it.
## Function signatures
- Take `T&` / `const T&` (or `T*` when null is meaningful) when the function only uses the object.
- Take `std::unique_ptr<T>` by value only when the function takes ownership; take `std::shared_ptr<T>` by value only when it shares ownership.
- Use `std::span<T>` (C++20) or iterator pairs for contiguous ranges instead of pointer plus length and pointer arithmetic.
- Use `std::vector` for dynamic arrays and `std::array` for fixed-size arrays instead of C arrays.
```cpp
#include <cstddef>
#include <memory>
#include <span>
#include <vector>
struct Texture {
explicit Texture(std::size_t size) : pixels(size) {}
std::vector<unsigned char> pixels;
};
// Non-owning parameter: the caller keeps ownership.
std::size_t non_zero(std::span<const unsigned char> data) {
std::size_t n = 0;
for (unsigned char b : data) n += (b != 0);
return n;
}
class Renderer {
public:
// Takes ownership: callers must std::move a unique_ptr in.
void adopt(std::unique_ptr<Texture> t) { textures_.push_back(std::move(t)); }
// Hands out a non-owning observer; valid while the Renderer owns it.
Texture* first() const { return textures_.empty() ? nullptr : textures_.front().get(); }
private:
std::vector<std::unique_ptr<Texture>> textures_;
};
```
## Moves
- Use `std::move` when you are done with a value and pass it to a new owner; do not use a moved-from object except to assign to or destroy it.
- Do not `std::move` a return value of a local variable (`return std::move(x);`); it blocks copy elision.
- Mark move constructors and move assignment `noexcept` so containers use them during reallocation.
## Common defects to prevent
- Dangling references: never return a pointer, reference, `std::string_view` or `std::span` to a local or temporary.
- Double ownership: never construct two smart pointers from the same raw pointer, and never `delete` memory a smart pointer owns.
- `shared_ptr` cycles: parent owns children with `shared_ptr`/`unique_ptr`, children point back with a raw pointer or `weak_ptr`.
- Invalidated observers: a `T*` into a `std::vector<T>` dangles after the vector reallocates; store indices or `unique_ptr` elements when you need stable addresses.
```cpp
struct Node {
std::vector<std::shared_ptr<Node>> children;
std::weak_ptr<Node> parent; // back-reference does not keep the parent alive
};
```
## Verify before finishing
Run these when they are available in the project:
- Build with warnings: `-Wall -Wextra` (and `-Werror` if the project uses it).
- Run tests with sanitizers: `-fsanitize=address,undefined` (AddressSanitizer also detects leaks on Linux; Valgrind is an alternative on Linux but does not support current macOS).
- `clang-tidy` with the `cppcoreguidelines-*` and `bugprone-*` checks, if configured.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
coding
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A C++20 rendering codebase built with CMake has this rule attached while a developer asks Cursor to refactor a class that stores textures with new/delete.
Refactor Renderer so it owns its Texture objects without manual delete, lets callers inspect the first texture, and counts non-zero bytes in a texture buffer.
Illustrative; not a recorded model run. Renderer stores std::vector<std::unique_ptr<Texture>>, adopt() takes unique_ptr by value and callers std::move into it, first() returns a non-owning Texture* that may be null, a free function takes std::span<const unsigned char>, no naked new/delete and no shared_ptr unless ownership is shared; plus a note to run the tests with -fsanitize=address,undefined.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/c-memory-management-modern.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "C++ Memory Management Modern: Ownership, Smart Pointers and Sanitizers project conventions"
globs: "**/*"
alwaysApply: false
---
# Modern C++ Memory Management
Applies to: C++ source and headers (`**/*.cpp`, `**/*.cc`, `**/*.h`, `**/*.hpp`) that allocate, own or reference objects.
Version baseline: checked against the C++ Core Guidelines and C++20 (`std::span` needs C++20; `std::make_unique` needs C++14). Read the build files (`CMakeLists.txt`, `CMAKE_CXX_STANDARD`, compiler flags) and follow the standard the project compiles with.
## Ownership rules
1. Every resource has exactly one clear owner, expressed in the type: a value, a container, `std::unique_ptr`, or (when ownership is really shared) `std::shared_ptr`.
2. No naked `new`/`delete` in application code. Create with `std::make_unique` / `std::make_shared`; prefer plain values and containers when no heap identity is needed.
3. A raw pointer `T*` or reference `T&` means "non-owning". Use them freely for parameters and observers whose lifetime is guaranteed by the caller.
4. Default to `std::unique_ptr`; use `std::shared_ptr` only when several owners must keep the object alive and no single owner can be named.
5. Use `std::weak_ptr` to observe a `shared_ptr`-managed object that may be destroyed while you hold the observer, and to break `shared_ptr` cycles. It is not a general-purpose observer pointer.
6. Wrap every other resource (files, sockets, locks, OS handles) in an RAII type whose destructor releases it.
## Function signatures
- Take `T&` / `const T&` (or `T*` when null is meaningful) when the function only uses the object.
- Take `std::unique_ptr<T>` by value only when the function takes ownership; take `std::shared_ptr<T>` by value only when it shares ownership.
- Use `std::span<T>` (C++20) or iterator pairs for contiguous ranges instead of pointer plus length and pointer arithmetic.
- Use `std::vector` for dynamic arrays and `std::array` for fixed-size arrays instead of C arrays.
```cpp
#include <cstddef>
#include <memory>
#include <span>
#include <vector>
struct Texture {
explicit Texture(std::size_t size) : pixels(size) {}
std::vector<unsigned char> pixels;
};
// Non-owning parameter: the caller keeps ownership.
std::size_t non_zero(std::span<const unsigned char> data) {
std::size_t n = 0;
for (unsigned char b : data) n += (b != 0);
return n;
}
class Renderer {
public:
// Takes ownership: callers must std::move a unique_ptr in.
void adopt(std::unique_ptr<Texture> t) { textures_.push_back(std::move(t)); }
// Hands out a non-owning observer; valid while the Renderer owns it.
Texture* first() const { return textures_.empty() ? nullptr : textures_.front().get(); }
private:
std::vector<std::unique_ptr<Texture>> textures_;
};
```
## Moves
- Use `std::move` when you are done with a value and pass it to a new owner; do not use a moved-from object except to assign to or destroy it.
- Do not `std::move` a return value of a local variable (`return std::move(x);`); it blocks copy elision.
- Mark move constructors and move assignment `noexcept` so containers use them during reallocation.
## Common defects to prevent
- Dangling references: never return a pointer, reference, `std::string_view` or `std::span` to a local or temporary.
- Double ownership: never construct two smart pointers from the same raw pointer, and never `delete` memory a smart pointer owns.
- `shared_ptr` cycles: parent owns children with `shared_ptr`/`unique_ptr`, children point back with a raw pointer or `weak_ptr`.
- Invalidated observers: a `T*` into a `std::vector<T>` dangles after the vector reallocates; store indices or `unique_ptr` elements when you need stable addresses.
```cpp
struct Node {
std::vector<std::shared_ptr<Node>> children;
std::weak_ptr<Node> parent; // back-reference does not keep the parent alive
};
```
## Verify before finishing
Run these when they are available in the project:
- Build with warnings: `-Wall -Wextra` (and `-Werror` if the project uses it).
- Run tests with sanitizers: `-fsanitize=address,undefined` (AddressSanitizer also detects leaks on Linux; Valgrind is an alternative on Linux but does not support current macOS).
- `clang-tidy` with the `cppcoreguidelines-*` and `bugprone-*` checks, if configured.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.