Unreal C++ Idioms

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Unreal C++ looks like ordinary C++ until the first line you copy from the standard library does not compile, or compiles and crashes the garbage collector. The engine has its own containers, strings, smart pointers, delegates, logging and assertions, and a coding standard that makes all of them read alike. Learning those idioms is most of the work of becoming fluent: the language is the same, the vocabulary is Epic’s.

The facts were checked in November 2026 against the Unreal Engine 5.8 documentation (5.8 was released on 2026-06-17; the latest hotfix at the time of writing is 5.8.4). The examples compile in a C++ project with the module Bookshelf (API macro BOOKSHELF_API, log category LogBookshelf) on any platform Unreal builds for. They continue the running example of the other pages: ABookActor, AShelfActor, ABookshelfGameState and ABookshelfPlayerController, with the shared model bookshelf.glb. The reflection macros are in UObject, Reflection and Garbage Collection; the plain-language C++ features are in the C++ section.

Naming and the coding standard

Epic’s coding standard is mandatory inside Epic and the model for everyone else; the Unreal Header Tool also enforces the class prefixes. The names follow PascalCase with no underscores in type and function names, and U.S. English spelling.

A class tree from UObject to ABookshelfCharacter and from UActorComponent and UPrimaryDataAsset to Bookshelf classes, next to a legend of the prefixes U, A, F, E, I, S, T and b with examples
Figure 1. Class prefixes and the Bookshelf classes that use them
Prefix Used for Bookshelf example

T

Template classes.

TArray, TMap, TSharedPtr

U

Classes that inherit from UObject.

UBookDataAsset, UBookshelfGameInstance

A

Classes that inherit from AActor.

ABookActor, ABookshelfGameMode

S

Classes that inherit from SWidget (Slate).

SBookTile

I

Abstract interface classes.

IBookInteractable

E

Enums.

EShelveResult

F

Most other classes and structs.

FBookRow, FVector

b

Boolean variables, as a prefix.

bIsHeld

The rest of the standard that matters in daily code:

  • Methods are verbs; booleans ask questions. GetDisplayTitle(), IsHeld(). Avoid vague verbs such as Handle and Process. A by-reference output parameter is prefixed Out (OutResult).

  • Portable types. Use int8, uint8, int16, int32, int64 and their unsigned forms, float and double. Use explicitly sized types for serialized and replicated data; plain int only when the width does not matter. The character type is TCHAR.

  • nullptr, never NULL. override and final on virtual overrides (write both virtual and override).

  • const everywhere it applies: parameters passed by const reference or pointer, methods that do not modify the object, iteration that does not modify the container. Never const on a by-value return type.

  • enum class, not namespaced enums, with ENUM_CLASS_FLAGS for bit flags. An enum exposed to Blueprint must be uint8.

  • auto is avoided, so that the type stays visible to the reader. It is allowed to bind a lambda, for very long iterator types and in template-heavy code; structured bindings are not allowed.

  • Braces on their own line, always, even for one statement; tabs of width four for indentation; switch statements end every case and have a default.

  • Pass UObject types by pointer, not by reference, so that a null is representable.

  • Avoid boolean flag parameters; use an enum or a parameter struct for long argument lists. Members are private by default.

  • Headers use #pragma once, forward declarations where possible and include only what they need ("include what you use").

  • New engine APIs live in a UE:: namespace. Never put a using declaration at global scope and never put a namespace around a UCLASS or USTRUCT.

  • Prefer Unreal containers and strings to the standard library ones; the standard library is for interop code. The standard <atomic>, <type_traits> and <cmath> headers are fine.

  • Comments say why, in JavaDoc style on the declaration; self-documenting names first.

Strings: FString, FName and FText

Unreal has three string types because a string can mean three different things.

Type What it is Use it for

FString

A mutable character array. It can be searched, modified and compared, and every instance stores its own characters.

Building text, parsing, file paths, anything you manipulate.

FName

A lightweight, immutable identifier. A global table stores each unique string once; an FName holds an index and an instance number, so comparison is a cheap integer comparison. It is case-insensitive and cannot be manipulated.

Asset names, bone and socket names, material parameter names, gameplay identifiers.

FText

The localization type: it carries a namespace and key so that translators can replace it, and it formats numbers, dates and plural forms for the user’s culture.

Everything the player reads: titles, labels, dialogue.

String literals are wrapped in TEXT("Book") so that they are stored as TCHAR (the native Unicode type) with no conversion; without it a literal is ANSI and must be converted. FString::Printf builds a string with printf-style formats, and FText::Format builds localized text from a pattern with {0} style or named placeholders. Mark user-facing literals with LOCTEXT (inside a namespace you define) or NSLOCTEXT; INVTEXT and AsCultureInvariant make text that must not be localized, such as a name from an external source.

Conversion How

FName to FString

Name.ToString()

FString to FName

FName(*Str) (lossy: case is discarded)

FString to FText

FText::FromString(Str) (not localized automatically)

FName to FText

FText::FromName(Name) (not localized automatically)

FText to FString

Text.ToString() (can lose information for some languages)

FText to FName

No direct conversion; go through FString, which is lossy.

int32 or float to FString

FString::FromInt(Value) and FString::SanitizeFloat(Value)

FString to int32 or float

FCString::Atoi(*Str) and FCString::Atof(*Str)

The * in *Str is a dereference operator that FString overloads to return the TCHAR pointer; you will write it constantly, because UE_LOG and Printf take TCHAR pointers for %s.

Containers: TArray, TMap and TSet

The three Unreal containers replace std::vector, std::unordered_map and std::unordered_set, with names, move semantics and garbage-collector support of their own.

flowchart TD Q1{"Do you look elements up by a key?"} -- "Yes, each key has a value" --> M["TMap"] Q1 -- "Yes, only membership matters" --> S["TSet"] Q1 -- "No" --> Q2{"Is order or index access needed?"} Q2 -- "Yes" --> A["TArray"] Q2 -- "No, just a bag" --> A2["TArray, or TSet when duplicates must be refused"]
  • TArray is a contiguous, resizable array. Add and Push copy or move an element in, Emplace constructs in place, AddUnique refuses duplicates, Insert places at an index, Append adds many. Remove erases every equal element, RemoveSingle the first, RemoveAt by index (check IsValidIndex first), and RemoveAll takes a predicate; the Swap variants are faster but do not keep order. Search with Contains, Find (an index or INDEX_NONE), FindByKey and FindByPredicate (a pointer or nullptr). Sort and HeapSort are unstable; StableSort keeps the order of equal elements. The unused capacity is called slack; Reset(n) and Empty(n) request it and Shrink releases it. The pointer from GetData is valid only until the next mutating operation.

  • TMap stores key-value pairs. A key needs operator== and a GetTypeHash overload (or custom key functions). Add replaces the value of an existing key; TMultiMap allows duplicate keys. Find returns a pointer to the value or nullptr and does one lookup. FindRef returns a copy or a default value without adding anything, FindOrAdd returns a reference after inserting a default, and operator[] asserts when the key is missing. Iteration order is not reliable, elements are not contiguous, and growth can invalidate pointers and references to elements.

  • TSet stores unique elements, where the element is its own key. Add, Contains, Remove and Find behave as above; iteration order is unspecified.

A UPROPERTY container of UObject pointers is how the garbage collector learns that the objects are in use; a plain member TArray<ABookActor*> is invisible to it. The collection below keeps the books in an array, counts copies per title in a map and tracks lending in a set.

// BookCatalog.h
#pragma once

#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "BookCatalog.generated.h"

class ABookActor;

UCLASS()
class BOOKSHELF_API UBookCatalog : public UObject
{
	GENERATED_BODY()

public:
	/** Adds a book to the catalog. Ignores nullptr after reporting it. */
	void Register(ABookActor* Book);

	/** Lends one copy. Returns false when the title is unknown or already lent. */
	bool CheckOut(FName BookId);

	int32 GetCopies(FName BookId) const;

	FText Describe(FName BookId) const;

	/** Drops destroyed books and orders the rest by title. */
	void Tidy();

private:
	/** A UPROPERTY, so the garbage collector sees the references. */
	UPROPERTY()
	TArray<TObjectPtr<ABookActor>> Books;

	TMap<FName, int32> Copies;
	TSet<FName> CheckedOut;
};
// BookCatalog.cpp
#include "BookCatalog.h"
#include "BookActor.h"
#include "Internationalization/Text.h"
#include "Bookshelf.h"

#define LOCTEXT_NAMESPACE "Bookshelf"

void UBookCatalog::Register(ABookActor* Book)
{
	// ensureMsgf reports once to the crash reporter and lets the game continue.
	if (!ensureMsgf(IsValid(Book), TEXT("UBookCatalog::Register received a null or destroyed book")))
	{
		return;
	}

	Books.AddUnique(Book);

	// FName is case-insensitive and cheap to compare, so it makes a good key.
	const FName BookId(*Book->GetDisplayTitle().ToString());
	int32& Count = Copies.FindOrAdd(BookId);
	++Count;
}

bool UBookCatalog::CheckOut(FName BookId)
{
	const int32* Count = Copies.Find(BookId);
	if (Count == nullptr || *Count <= 0 || CheckedOut.Contains(BookId))
	{
		return false;
	}

	CheckedOut.Add(BookId);
	UE_LOG(LogBookshelf, Log, TEXT("%s checked out"), *BookId.ToString());
	return true;
}

int32 UBookCatalog::GetCopies(FName BookId) const
{
	return Copies.FindRef(BookId);
}

FText UBookCatalog::Describe(FName BookId) const
{
	FFormatNamedArguments Args;
	Args.Add(TEXT("Title"), FText::FromName(BookId));
	Args.Add(TEXT("Copies"), GetCopies(BookId));
	return FText::Format(LOCTEXT("CatalogLine", "{Title}: {Copies} copies"), Args);
}

void UBookCatalog::Tidy()
{
	Books.RemoveAll([](const TObjectPtr<ABookActor>& Book)
	{
		return !IsValid(Book);
	});

	Books.Sort([](const TObjectPtr<ABookActor>& A, const TObjectPtr<ABookActor>& B)
	{
		return A->GetDisplayTitle().CompareTo(B->GetDisplayTitle()) < 0;
	});
}

#undef LOCTEXT_NAMESPACE

Delegates

A delegate is a type-safe, serializable-or-not function pointer with a binding list, Unreal’s version of the observer pattern (compare a C# event). Epic documents three kinds, and each is available in single-cast and multicast form.

ABookActor with a dynamic multicast and a native multicast delegate, four listeners bound to them with AddDynamic, a Blueprint Assign node, AddUObject and AddWeakLambda, and a table of the three delegate macro families
Figure 2. The delegate kinds in the Bookshelf
Kind Declared with Properties

Single-cast

DECLARE_DELEGATE, DECLARE_DELEGATE_OneParam, DECLARE_DELEGATE_RetVal_OneParam and so on

At most one binding; may return a value and may be const. Fire with Execute (asserts when unbound) or ExecuteIfBound; test with IsBound.

Multicast

DECLARE_MULTICAST_DELEGATE, DECLARE_MULTICAST_DELEGATE_OneParam and so on

Many bindings, no return value, undefined call order. Fire with Broadcast, which is safe with no bindings. Remove with Remove (a handle) or RemoveAll(this).

Dynamic

DECLARE_DYNAMIC_DELEGATE, DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam and so on

Serializable and reflected: bound functions are found by name and must be UFUNCTION. Slower than the other kinds. Bind with BindDynamic and AddDynamic, remove with RemoveDynamic. Only this kind can be a BlueprintAssignable property.

Signatures allow up to eight parameters and, for single-cast kinds, up to four payload values passed at bind time. Declarations may sit at global scope, in a namespace or inside a class, not inside a function body. A delegate type carries the F prefix, and by convention ends in a name that describes the moment (FOnScoreChangedNative).

The binding function chooses how safe the binding is:

  • BindUObject and AddUObject keep a weak reference to a UObject; a destroyed object is skipped. BindSP and AddSP do the same for a TSharedPtr owner (not thread-safe).

  • BindRaw and AddRaw store a raw pointer with no lifetime tracking. Executing after the object is deleted is undefined behaviour; avoid them for UObject.

  • BindLambda and AddLambda store a functor, and are safe only when the lambda captures nothing that can die. BindWeakLambda and AddWeakLambda take a UObject and run the lambda only while it is alive; AddSPLambda does the same for a shared pointer.

  • BindStatic and AddStatic bind a free or static function.

Delegates are safe to copy but allocate when passed by value, so pass them by reference. Never read the return value of an unbound delegate: Execute on an unbound single-cast delegate asserts, and an unbound delegate with output parameters can leave them uninitialized, so test with IsBound or use ExecuteIfBound when there is no return value.

// BookshelfGameState.h (excerpt)
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/GameStateBase.h"
#include "BookshelfGameState.generated.h"

DECLARE_MULTICAST_DELEGATE_OneParam(FOnScoreChangedNative, int32 /*NewScore*/);

UCLASS()
class BOOKSHELF_API ABookshelfGameState : public AGameStateBase
{
	GENERATED_BODY()

public:
	void AddScore(int32 Delta);

	int32 GetScore() const { return Score; }

	/** Native listeners (C++ only). Blueprints use a dynamic delegate instead. */
	FOnScoreChangedNative OnScoreChanged;

protected:
	UPROPERTY(BlueprintReadOnly, Category = "Bookshelf")
	int32 Score = 0;
};
// BookshelfPlayerController.h (excerpt)
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "BookshelfPlayerController.generated.h"

class ABookshelfGameState;

UCLASS()
class BOOKSHELF_API ABookshelfPlayerController : public APlayerController
{
	GENERATED_BODY()

protected:
	virtual void BeginPlay() override;
	virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;

private:
	void HandleScoreChanged(int32 NewScore);

	TWeakObjectPtr<ABookshelfGameState> WatchedState;
	FDelegateHandle ScoreHandle;
};
// BookshelfGameState.cpp and BookshelfPlayerController.cpp (excerpts)
void ABookshelfGameState::AddScore(int32 Delta)
{
	Score += Delta;
	OnScoreChanged.Broadcast(Score);
}

void ABookshelfPlayerController::BeginPlay()
{
	Super::BeginPlay();

	if (ABookshelfGameState* State = GetWorld()->GetGameState<ABookshelfGameState>())
	{
		WatchedState = State;
		ScoreHandle = State->OnScoreChanged.AddUObject(this, &ABookshelfPlayerController::HandleScoreChanged);

		// A second listener that disappears with this controller. The weak lambda is
		// skipped once 'this' has been destroyed.
		State->OnScoreChanged.AddWeakLambda(this, [this](int32 NewScore)
		{
			UE_LOG(LogBookshelf, Verbose, TEXT("%s saw score %d"), *GetName(), NewScore);
		});
	}
}

void ABookshelfPlayerController::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	if (ABookshelfGameState* State = WatchedState.Get())
	{
		State->OnScoreChanged.Remove(ScoreHandle);
	}

	Super::EndPlay(EndPlayReason);
}

void ABookshelfPlayerController::HandleScoreChanged(int32 NewScore)
{
	UE_LOG(LogBookshelf, Log, TEXT("Score changed to %d"), NewScore);
}

A single-cast delegate is the right tool for "ask exactly one party a question". The shelf asks whichever rule is bound whether a book may be shelved:

// ShelfActor.h (excerpt)
DECLARE_DELEGATE_RetVal_OneParam(bool, FCanShelveBook, const ABookActor* /*Book*/);

// In the class body:
FCanShelveBook CanShelveRule;

// ShelfActor.cpp (excerpt)
bool AShelfActor::IsBookAllowed(const ABookActor* Book) const
{
	// Execute on an unbound delegate would assert, so test first.
	return !CanShelveRule.IsBound() || CanShelveRule.Execute(Book);
}

// Binding elsewhere, for example in the game mode:
Shelf->CanShelveRule.BindLambda([](const ABookActor* Book)
{
	return IsValid(Book);
});

The Epic standard adds rules for lambdas: keep them short, capture explicitly instead of [&] or [=], never capture locals or members by reference for deferred execution, and do not let this or a UObject pointer hide in a capture that the garbage collector cannot see. For deferred execution use CreateWeakLambda or AddWeakLambda (which unbind when the object dies), or capture a TWeakObjectPtr and validate it inside.

Logging

UE_LOG takes a category, a verbosity and a TEXT format. Declare one category per module so that you can filter and raise its verbosity independently. In the header, below the includes, use DECLARE_LOG_CATEGORY_EXTERN(Name, DefaultVerbosity, CompileTimeVerbosity); in one source file, DEFINE_LOG_CATEGORY(Name).

// Bookshelf.h
#pragma once

#include "CoreMinimal.h"

DECLARE_LOG_CATEGORY_EXTERN(LogBookshelf, Log, All);

// Bookshelf.cpp
#include "Bookshelf.h"
#include "Modules/ModuleManager.h"

DEFINE_LOG_CATEGORY(LogBookshelf);

IMPLEMENT_PRIMARY_GAME_MODULE(FDefaultGameModuleImpl, Bookshelf, "Bookshelf");
Verbosity Behaviour

Fatal

Always printed, then crashes the session.

Error

Printed to the console and the log; shown in red.

Warning

Printed to the console and the log; shown in yellow.

Display

Printed to the console and the log; shown in grey.

Log

Written to the log only.

Verbose, VeryVerbose

Not printed by default; appear only when enabled for the category. Use them for detailed traces.

Raise verbosity without recompiling: type log LogBookshelf verbose in the console, or start the game with -LogCmds="LogBookshelf Verbose" (an all category sets every category at once). Format values with %s for strings (pass an FString as *Name), %d for integers and %f for floats; print a boolean by choosing between TEXT("true") and TEXT("false").

UE_LOGFMT (added in UE 5.2, header Logging/StructuredLog.h) is the structured form: a format with named placeholders and values that stay separate fields in the log, positional or named but never both in one call.

#include "Logging/StructuredLog.h"

void ABookActor::LogPull(const AActor* Puller) const
{
	UE_LOGFMT(LogBookshelf, Log, "{Book} was pulled by {Puller}",
		("Book", GetNameSafe(this)), ("Puller", GetNameSafe(Puller)));

	if (GEngine)
	{
		// Key -1 adds a new message every call; use a fixed key to replace an existing one.
		GEngine->AddOnScreenDebugMessage(-1, 2.0f, FColor::Yellow, TEXT("Book pulled"));
	}
}

Source: Epic: Logging

Assertions: check, verify and ensure

Macro On failure When it is active

check, checkf, checkNoEntry, checkNoReentry, unimplemented

Halts execution.

Debug and Development builds; compiled out of Test and Shipping unless USE_CHECKS_IN_SHIPPING=1 (leave it at its default of 0 for a shipping product). The expression is not evaluated when compiled out.

checkSlow, checkfSlow

Halts execution.

Debug builds only. Use for expensive checks.

verify, verifyf

Halts execution.

Debug, Development, Test and Shipping Editor builds. The expression is always evaluated, so it may have side effects.

ensure, ensureMsgf

Reports to the crash reporter once per session and continues.

The expression is evaluated in all builds; reporting happens in Debug, Development, Test and Shipping Editor builds.

ensureAlways, ensureAlwaysMsgf

As ensure, but reports every time.

Same as ensure.

Use check for conditions with no side effects, verify when the expression must run in every build, ensure for a recoverable error that you still want to hear about, and checkNoEntry for an impossible switch default. Never put a side effect inside check: the Shipping build removes it.

Source: Epic: Asserts

Safe pointers

IsValid(Object) is the correct test for a UObject pointer: it is false for nullptr and for an object that is pending destruction, which a plain null test misses. A TWeakObjectPtr observes an object without keeping it alive; call Get() and test the result. Use a UPROPERTY (or TObjectPtr member) for pointers that must keep an object alive, and TSharedPtr and MakeShared for plain C++ objects that are not UObject. The garbage-collection rules and the full pointer family are on UObject, Reflection and Garbage Collection; the language-level equivalents are in C++ memory management and smart pointers.

Common mistakes

  • A raw UObject pointer member without UPROPERTY. The garbage collector does not see it, the object can be destroyed, and the pointer dangles. Use UPROPERTY() with a TObjectPtr, or a TWeakObjectPtr when you do not own the object.

  • Using standard containers or std::string for engine data. They do not integrate with garbage collection, serialization or Blueprint; use them only at interop boundaries.

  • A literal without TEXT. FString Name = "Book"; compiles through a conversion; the standard requires TEXT("Book").

  • Passing an FString to %s without .* The format reads the object bytes as characters; always pass *Str.

  • Using FName where text is shown to the player. An FName is case-insensitive and cannot be localized; show FText.

  • Binding a raw pointer or a plain lambda to a delegate on an object that can die. Use AddUObject, AddWeakLambda or a TWeakObjectPtr guard.

  • Forgetting UFUNCTION() on an AddDynamic target. It compiles and never fires.

  • Execute on an unbound single-cast delegate. It asserts; test IsBound or use ExecuteIfBound.

  • Never unbinding. A multicast delegate that outlives its listener leaks bindings; store the FDelegateHandle and call Remove, or use RemoveAll(this) in EndPlay.

  • Side effects inside check. The expression disappears in Shipping; use verify.

  • Indexing a TMap with operator[] for a missing key. It asserts. Use Find, which returns a pointer or nullptr.

  • Holding a pointer to a container element across an Add. Growth reallocates and invalidates it.

  • Relying on TMap or TSet iteration order. It is unspecified.

Performance notes

  • TArray is contiguous, so iteration and sorting are cache-friendly; prefer it to TMap for small collections searched linearly, where hashing costs more than a scan. Reserve-like control comes from Reset(n) and Empty(n): size an array once when the count is known to avoid repeated growth.

  • Emplace constructs in place and avoids a temporary; RemoveSwap and RemoveAtSwap avoid shifting elements when order does not matter.

  • FName comparison is an integer compare, but creating an FName from a string hashes the string and consults the name table. Cache names that you use every frame in a static const FName, as ApplyCoverColor does with the cover colour parameter.

  • FString allocates; building strings every frame creates garbage. Log with Verbose for per-frame traces so that they cost nothing unless enabled.

  • Dynamic delegates are slower than native ones (name lookup, reflection). Use them where Blueprint must listen, and native multicast delegates for C++-only events.

  • Pass TArray, FString and delegates by const reference; pass by value only to move into a member with MoveTemp.

  • ensure evaluates its expression in every build; keep expensive conditions in checkSlow.

What changed recently

Version Change

UE 5.0 (2022)

TObjectPtr was introduced for UObject pointer members, and Blueprint nativization was removed.

UE 5.2 (2023)

UE_LOGFMT structured logging was added (header Logging/StructuredLog.h).

UE 5.8 (2026)

The documentation for the coding standard, containers, delegates, logging and asserts used here is unchanged in substance; the Epic standard asks for explicit lambda captures and weak delegate bindings, as shown above.

See also