1. Home
  2. Explore
  3. Computer Science
  4. Bjarne Stroustrup Technology Lecture

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Bjarne Stroustrup Technology Lecture

C++: Design, Resource Management, and Generic Programming

What C++ Is Designed to Do

C++ is intended for building efficient abstractions: software that offers high-level concepts while retaining performance and control close to the hardware. Its primary strengths are in systems software, infrastructure, embedded and resource-constrained applications, and large programs where performance matters.

The language aims to balance several goals:

  • Type safety: The compiler should catch as many invalid operations as practical before a program runs.

  • Resource safety: Programs should acquire and release resources reliably, including memory, files, locks, and connections.

  • Performance: High-level abstractions should not automatically impose unnecessary runtime costs.

  • Predictability: Some systems, especially real-time and safety-critical systems, require operations to have predictable execution costs.

  • Abstraction: Programmers should be able to express domain-specific ideas as types and operations rather than manipulate low-level details everywhere.

  • Usability and readability: Code should be understandable by both people and tools, and its complexity should be reasonably related to the task.

These goals can conflict. For example, a mechanism that provides convenient sharing may add synchronization costs, while a feature that improves safety may restrict low-level operations. C++ design therefore involves balancing flexibility, compatibility, performance, and safety rather than maximizing just one property.

C++ is not intended to be the simplest language for every task. Its design emphasizes demanding applications where resource control and performance are important. It is also not enough for a language to be useful only to experts: making safe, modern techniques accessible to less-experienced programmers is an important design goal.


The Ideas Behind C++

C++ brings together several traditions in programming language design.

C: A model close to the machine

C provides a relatively direct model of hardware operations and memory. Its arrays, structures, and basic operations make it useful for low-level work and provide programmers with substantial control.

That low-level model can also make it easy to lose important information. For example, when an array is treated as a pointer, its size may no longer be available. This can contribute to errors such as accessing memory beyond an array’s bounds.

Fortran: Programming in terms of problems

Fortran raised the level of programming above direct machine manipulation. It was designed for scientific and engineering work, making it easier to express calculations in terms of the problem being solved. Its adoption across different machines also helped demonstrate the value of portability.

Simula: Programmers define their own abstractions

Simula introduced the idea that programmers could build abstractions appropriate to their own domains rather than rely only on types built into a language. Its classes and class relationships helped establish ideas later associated with object-oriented programming.

C++: Low-level control combined with abstraction

C++ combines a C-like ability to work close to the machine with facilities for defining higher-level types and interfaces. A programmer can represent data and operations together in a class, while still aiming to produce efficient code.

This combination explains much of the language’s flexibility—and some of its complexity. The language supports both direct low-level programming and powerful abstractions, so programmers must choose appropriate techniques for each problem.


Long-Lived Software and Compatibility

Software often outlives the hardware and teams for which it was first written. A language can take many years to mature into widespread industrial use, and systems built with it may remain in service for decades.

That longevity makes backward compatibility important. A change that improves a language but breaks existing programs may impose significant costs on organizations maintaining large codebases. As a result, older features and rules can remain even when newer techniques are safer or clearer.

This creates a trade-off:

  • Keeping old behavior helps existing programs continue to compile.

  • Removing or changing old behavior can make the language simpler and safer.

  • Maintaining both old and new approaches adds complexity.

The accumulated older features are sometimes described as “barnacles.” In practice, they are difficult to remove when users rely on them. Deprecation warnings or options to disable old behavior may help, but programmers and organizations often prioritize keeping established code working.


Type Safety and Systems Programming

Type safety means that the language and compiler help prevent operations from being applied to inappropriate kinds of values. C++ has developed over time toward stronger type checking, but doing so must be balanced against performance, compatibility, and the needs of low-level programming.

A systems language must sometimes let programmers manipulate memory and hardware directly. At the same time, unrestricted low-level operations can produce errors such as invalid memory access. A central challenge is to make safe operations convenient while preserving an escape hatch for situations that genuinely require low-level control.

The desired outcome is not merely that experts can write sophisticated code. It is that programmers can write code whose safety and performance properties are easier to understand and check.


Resource Management and RAII

A resource is something a program acquires and must eventually release. Common examples include:

  • Memory

  • File handles

  • Network connections

  • Locks

  • Threads and other operating-system resources

A program can leak a resource when it acquires it but fails to release it. For instance, a function may open a file and then exit early without closing it. Such failures can accumulate until a program runs out of memory, file handles, or another limited resource.

A resource should have a clear owner: an object or part of the program responsible for releasing it. Ambiguous ownership is a common source of bugs. If a pointer to an object is passed elsewhere, it may become unclear which part of the program must eventually destroy the object.

Resource Acquisition Is Initialization

C++ uses RAII, short for Resource Acquisition Is Initialization. Under this approach:

  1. An object acquires a resource when it is constructed.

  2. The object’s destructor releases the resource when the object’s lifetime ends.

This makes resource cleanup follow the lifetime of an object. When execution leaves a scope—whether normally, through an early return, or because an exception is thrown—the relevant destructors run.

RAII is useful because cleanup does not have to be manually repeated along every possible path through a function. A well-designed resource-managing class establishes its invariant in its constructor and releases or dismantles the resource in its destructor.

RAII connects resource ownership to object lifetime, so cleanup happens automatically when the owning object goes out of scope.

Standard Library Containers and Handles

Many standard-library types follow the RAII model. A vector, string, map, stream, or smart pointer can manage resources internally and release them when its lifetime ends.

For example, a vector owns its elements and the storage used for them. When the vector is destroyed, it releases that storage and destroys its elements. If those elements are themselves resource-managing objects, their destructors run as well. This allows cleanup to be composed across layers of objects.


Smart Pointers and Ownership

Raw pointers can refer to objects, but by themselves they do not clearly state who owns those objects or who must destroy them. Smart pointers provide ownership models that make these responsibilities more explicit.

std::unique_ptr: One clear owner

A unique pointer represents exclusive ownership. When the unique pointer is destroyed, it destroys the object it owns.

It is appropriate when one part of a program is responsible for an object’s lifetime. It also makes transfer of ownership explicit: ownership can move from one unique pointer to another, but it is not copied as if there were several independent owners.

Unique ownership is generally simpler and cheaper than shared ownership because it does not need to maintain a shared reference count.

std::shared_ptr: Shared ownership

A shared pointer represents an object whose lifetime is jointly managed by multiple owners. Copies of the shared pointer share ownership, and the object is destroyed when the last owner releases it.

Shared pointers use a reference count to track the number of owners. Updating that count is shared work, and sharing can introduce costs, particularly in concurrent programs. Shared ownership should therefore be used when the program genuinely has multiple owners—not simply as a general-purpose replacement for raw pointers.

References and non-owning pointers

Not every pointer-like value owns an object. A reference or non-owning pointer may simply provide access to an object whose lifetime is controlled elsewhere. In that case, the program must ensure that the referenced object remains alive for as long as the access path is used.

A useful ownership distinction is:

  • Owning handle: Responsible for the object’s lifetime.

  • Non-owning reference or pointer: Provides access but does not determine when the object is destroyed.

Making this distinction explicit helps prevent leaks and dangling references.


Returning Large Objects and Move Semantics

Functions often need to produce objects, such as a newly constructed matrix or container. A matrix may contain a large number of elements, so returning it by copying could be expensive.

Several approaches have drawbacks:

  • Returning a raw pointer leaves ownership and deletion responsibilities unclear.

  • Returning a reference does not solve ownership; the referenced object still needs a well-defined lifetime.

  • Requiring a caller-provided output object can make ordinary operations awkward and less expressive.

For an operation such as matrix addition, a natural interface is to return a matrix representing the result. C++ supports this efficiently through move semantics.

Copying versus moving

A copy duplicates an object’s represented value. A move transfers resources from one object to another when the source object is no longer needed in its former role.

For an object that owns a large block of memory, moving can often transfer a small amount of ownership information rather than duplicate all the elements. After the transfer, the source object is left in a valid state that can be safely destroyed.

A move constructor describes how to create an object by taking resources from another object. A copy constructor describes how to create an independent copy. If a type is composed of members that already manage copying and moving correctly, the compiler can often generate the appropriate operations.

Why moves support value-style interfaces

Move semantics allow functions to return objects by value without requiring programmers to expose raw ownership details. This supports interfaces that read naturally—for example, an operation that returns the sum of two matrices—while avoiding unnecessary copying in common cases.

Compilers may also eliminate some copies or moves when returning values. Correct code should express the desired value-level operation; the language and compiler can then use permitted optimizations to make it efficient.


Garbage Collection and Deterministic Cleanup

Garbage collection automatically reclaims some memory that is no longer reachable by a program. It can reduce certain kinds of memory-management errors, but it does not handle every resource.

Limitations of garbage collection

Garbage collection is not a complete resource-management solution because:

  • Many important resources are not memory. Files, locks, connections, and operating-system handles also need timely release.

  • Collection may occur at a time chosen by the runtime rather than immediately when a resource is no longer needed.

  • Some collection strategies require bookkeeping or coordination among parts of a program.

In systems where timing and resource use must be predictable, delayed cleanup can be problematic. RAII instead connects cleanup to the end of an object’s lifetime.

Shared ownership has costs

Shared ownership can also make lifetime management more complex. In concurrent software, shared state may require coordination, and that coordination can reduce performance. The appropriate design depends on whether the program truly needs shared ownership.

Garbage collection can nevertheless be useful for existing systems that cannot easily be converted to explicit ownership. In some designs it can serve as an occasional cleanup mechanism. The important distinction is that automatic memory collection does not remove the need to reason about all other resources or about ownership relationships.


Object-Oriented Programming

Object-oriented programming organizes code around objects and classes. A class can define data, operations on that data, and an interface through which other code uses it.

Inheritance and polymorphism

Inheritance is useful when the problem domain contains a genuine hierarchy of related concepts. For example, circles and triangles can be treated as particular kinds of shapes. A program can then use a common interface for all shapes while letting each concrete type implement behavior such as drawing itself.

With runtime polymorphism, a call through a base-class interface can invoke the implementation appropriate to the object’s actual type. Virtual functions enable this kind of dispatch.

The technique is valuable when objects share an interface but differ in their implementations. However, it is not appropriate for every relationship, and deep or elaborate class hierarchies can make programs difficult to understand and maintain.

Costs and limits of runtime polymorphism

Virtual calls have some runtime cost, though that cost can be small in many situations. A more important limitation is that indirect calls may make it harder for the compiler to inline the called function. In high-performance code, inlining can matter when the operation is small and called frequently.

Inheritance can also encourage allocation and indirection. These costs may be acceptable when polymorphism expresses a real design need, but inheritance should not be treated as a requirement for good programming.

Access control and invariants

C++ classes provide public, protected, and private access levels. Private data supports encapsulation: a class can restrict how its internal representation is modified and protect the conditions that must remain true for its objects.

Protected data can make it easier for derived classes to access a base class’s internals, but it can also weaken that protection. If many derived classes depend on internal data, preserving the base class’s invariants becomes more difficult. A carefully designed interface is often safer than exposing representation details through inheritance.

Abstract classes and interfaces

An abstract class can define an interface that derived classes are expected to implement. This supports a common contract across different types. C++ also supports implementation inheritance, in which derived classes reuse code from a base class.

Interface inheritance and implementation inheritance serve different purposes. Both can be useful, but they should be chosen deliberately rather than used simply because a language supports them.


Generic Programming and Templates

Generic programming expresses algorithms and data structures in terms of types or operations that can vary. A vector, for example, can be a vector of integers, strings, or another type without requiring a separate vector implementation for each element type.

Templates allow C++ code to be parameterized by types and, in some cases, values. The compiler generates code for particular template arguments when the program is compiled.

Generic algorithms and iterator ranges

Generic algorithms are commonly written to work with ranges described by iterators rather than with one specific container. An algorithm such as sorting can then operate on different containers or parts of containers, provided those iterators support the operations the algorithm requires.

A range is commonly represented by a beginning position and an end position. This permits an algorithm to work on a whole sequence or a subrange of it.

The requirements depend on the algorithm. For example, the standard sorting algorithm requires random access to the elements. A linked list does not provide that kind of access, so it is not a suitable argument to that sorting algorithm; a list provides its own sorting operation instead.

Predicates and function objects

Some algorithms accept a predicate: an operation that answers a question about an element, such as whether it satisfies a condition. A predicate can also define a custom ordering.

A function object is an object that can be called like a function. It can carry state as well as behavior. A lambda expression offers a concise way to write such behavior directly where an algorithm is used.

For instance, a search can use a predicate that compares strings according to a particular rule. This lets the algorithm remain general while the caller supplies the comparison behavior appropriate to the task.

Compile-time checking and diagnostics

Templates are often described as using “duck typing”: if the operations required by the template work for a type, the type can be used. If an operation is missing or invalid, compilation fails.

This approach is flexible, but without clearly stated requirements, a compiler error may occur deep inside template code and produce a long, confusing diagnostic. The error may mention implementation details rather than explain which requirement the supplied type failed to meet.

Concepts provide a way to state requirements on template arguments. A concept can describe properties such as whether a type supports comparison, whether a container permits random access, or whether an operation can be applied to its elements.

Concepts improve generic programming by:

  • Documenting the intended requirements of an algorithm or type.

  • Rejecting unsuitable arguments closer to the point of use.

  • Producing more informative diagnostics.

  • Helping programmers distinguish a type’s interface from the details of a template’s implementation.

Compile-time computation

C++ templates can be used for computations during compilation, a technique called template metaprogramming. This can improve performance or express some computations before runtime, but complex template metaprogramming can be difficult to read and diagnose.

Compile-time functions and constraints can often express such work more directly. A general design principle is to use ordinary, clear code where possible, reserving complicated compile-time techniques for cases where they provide a real benefit.


Combining Programming Styles

C++ supports object-oriented, generic, procedural, and functional techniques. These styles are not mutually exclusive.

A single program may use:

  • A class hierarchy to model runtime-varying shapes.

  • A generic algorithm to traverse a container of those shapes.

  • A lambda expression to supply an operation to the algorithm.

  • RAII objects to manage the container’s resources.

This is a reason not to treat programming “paradigms” as competing camps. New techniques often extend what can be expressed without making older techniques useless. Object-oriented programming remains appropriate for some problems, while generic algorithms or direct procedural code may be clearer for others.

The key question is whether a technique fits the problem, not whether a program follows one style exclusively.


Safer Containers and Buffer Overflows

C-style arrays provide direct access to memory but can make it easy to lose track of the number of elements they contain. If code accesses beyond the end of an array, it can read or overwrite memory that does not belong to that array. Such errors can cause crashes, corrupt data, or create security vulnerabilities.

Containers such as vectors retain size information and provide operations that make their intended use clearer. Using a container’s size when writing loops reduces the chance of hard-coded bounds being incorrect. Containers do not make every program automatically safe, but they can make common mistakes less likely.

Smart pointers can likewise make ownership clearer than unstructured use of raw pointers. Safer abstractions are most effective when they are used consistently and when low-level operations are limited to parts of the program that need them.

Hardware support and compiler checks can further help detect out-of-bounds accesses. Such mechanisms can strengthen safety, but they do not eliminate the need for sound ownership and bounds reasoning throughout a program.


Challenges in Large C++ Codebases

C++ permits many ways to express a design. That flexibility can produce excellent code, but it also allows programs to become unnecessarily complicated.

New developers may find large projects difficult to understand when they combine:

  • Deep class hierarchies.

  • Extensive template metaprogramming.

  • Complex interactions among templates and inheritance.

  • Raw pointers with unclear ownership.

  • Multiple coding styles accumulated over many years.

A codebase’s difficulty can also reflect its age and history rather than a single language feature. A large system may contain code written under different conventions, compiler constraints, and design assumptions.

Improving maintainability

Useful approaches include:

  • Prefer straightforward designs over the most intricate technique available.

  • Use clear ownership models and standard resource-managing types.

  • Limit template metaprogramming when simpler code can express the same idea.

  • State template requirements explicitly where possible.

  • Use static-analysis tools to find errors and risky patterns.

  • Use code transformation and modernization tools to update old code incrementally.

  • Teach safer modern practices rather than presenting obsolete or error-prone techniques as the default.

No language feature prevents all poor design. The same language can be used to write both robust and fragile programs.


Compilation Time and Modules

Template-heavy C++ projects can take a long time to compile. One contributing factor is that header files may be processed repeatedly across many source files. The same declarations and template definitions can therefore be parsed and compiled many times.

Modules are intended to reduce repeated work and improve the organization of interfaces. Instead of relying entirely on textual inclusion, a module system can allow compiled interfaces to be reused. This offers a language-level route to improving compilation workflows, although actual benefits depend on compiler support and how a project is structured.


Compatibility Between Compilers

C++ does not provide one universally adopted binary interface that makes code produced by every compiler interchangeable. A binary interface includes conventions such as symbol naming, object layout, and how functions call one another.

This can make it difficult to combine libraries compiled with different compilers or compiler versions. Compiler vendors often prioritize compatibility with their own earlier releases, because users need existing programs and libraries to continue working.

Source compatibility and binary compatibility are different:

  • Source compatibility concerns whether source code can still be compiled.

  • Binary compatibility concerns whether already-compiled components can work together without being rebuilt.

Achieving broad compatibility across compilers would be useful, but established differences and the need to preserve existing ecosystems make it difficult.


Modernizing C++ Code

Adoption of newer standards can be slow when organizations maintain large codebases that must work with older compilers. Modernization is not merely a matter of changing the language version: programmers must understand new practices, and organizations need confidence that changes preserve behavior.

Modern techniques can improve safety and may produce efficient code. Migration is therefore helped by:

  • Clear examples showing how newer idioms replace older patterns.

  • Compiler and analysis tools that identify outdated or unsafe code.

  • Automated transformations that update code consistently.

  • A coordinated approach to compiler versions and project conventions.

Large codebases are rarely modernized all at once. They may contain old and new code for many years, so tools and conventions that support gradual change are valuable.


Choosing Language Features and Language Boundaries

The speaker’s design goals suggest that C++ should improve without abandoning its ability to work close to hardware. Turning it into a highly specialized language for one domain could undermine its usefulness as a general systems language.

Creating an entirely new language is also difficult. A new language needs not only good features but also an ecosystem: compilers, libraries, tools, trained developers, and established code. Without that infrastructure, an elegant design may still fail to gain adoption.

Some areas—such as hardware-description languages—have requirements that differ from ordinary application programming. C++ features such as templates may be useful in some hardware-oriented work, but the best language relationship depends on the specific task.


Key Principles

  • Use abstractions that preserve control: High-level interfaces can make code clearer without requiring avoidable runtime overhead.

  • Make ownership explicit: Every resource should have a clear owner, and non-owning access should not be confused with ownership.

  • Tie cleanup to lifetime: RAII makes resource release reliable across normal exits, early returns, and exceptions.

  • Prefer value-oriented interfaces where practical: Move semantics allow large objects to be returned naturally without requiring raw-pointer ownership conventions.

  • Use inheritance for real hierarchies: Runtime polymorphism is useful when objects share an interface and have different implementations, but it is not a universal design rule.

  • Use generic algorithms with explicit requirements: Templates support reuse across types, while concepts can make those requirements clearer.

  • Treat language styles as complementary: Object-oriented, generic, procedural, and functional techniques can work together.

  • Improve old code incrementally: Compatibility and the long lifetime of software make tooling, analysis, and gradual modernization essential.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent