Abseil C++

An open-source collection of C++ library code designed to augment the C++ standard library

  • Abseil Platform Support Update

    Abseil Platform Support Update

    By Derek Mauro, Abseil Engineer

    In September 2017, Abseil made the following support promise:

    We will support our code for at least 5 years. We will support language versions, compilers, platforms, and workarounds as needed for 5 years after their replacement is available, when possible. If it is technically infeasible (such as support for MSVC before 2015, which has limited C++11 functionality), those will be noted specifically. After 5 years we will stop support and may remove workarounds. ABSL_HAVE_THREAD_LOCAL is a good example: the base language feature works on everything except Xcode prior to Xcode 8 ; once Xcode 8 is out for 5 years, we will drop that workaround support.

    The ability to evolve over time has long been a goal of the Abseil (...)

  • Tip of the Week #116: Keeping References on Arguments

    Originally posted as TotW #116 on May 26, 2016

    By Alex Pilkiewicz

    Updated 2020-06-01

    Quicklink: abseil.io/tips/116

    From painting to image, from image to text, from text to voice, a sort of imaginary pointer indicates, shows, fixes, locates, imposes a system of references, tries to stabilize a unique space. — This is Not a Pipe by Michel Foucault

    Const References vs. Pointers to Const

    Used as arguments of functions, const references have several advantages when compared to pointers to const: they cannot be null and it’s quite clear that the function is not taking ownership of the object. But they have other differences that can sometimes be problematic: they are more implicit (i.e. there is nothing on the call site showing we are taking a reference) and they can be bound to a temporary. (...)

  • Tip of the Week #165: if and switch statements with initializers

    Originally posted as TotW #165 on August 17, 2019

    By Thomas Köppe

    Updated 2020-01-17

    Quicklink: abseil.io/tips/165

    Unless you use conditional control flow, you can stop reading now.

    A new syntax

    C++17 allows if and switch statements to include an initializer:

    if (init; cond) / ... / switch (init; cond) / ... /

    This syntax lets you keep the scope of variables as tight as possible:

    if (auto it = m.find("key"); it != m.end()) return it->second; else return absl::NotFoundError("Entry not found");

    The semantics of the initializer are exactly as in the for statement; details below.

    When this is useful

    One of the most important ways to manage complexity is to break complex systems down into non-interacting, local parts that can be understood in isolation and ignored in their (...)

  • Tip of the Week #181: Accessing the value of a StatusOr

    Originally posted as TotW #181 on July 9, 2020

    By Michael Sheely

    Updated 2020-09-02

    Quicklink: abseil.io/tips/181

    StatusOr: you don’t have to choose!

    When the time comes to access the value inside an absl::StatusOr object, we should strive to make that access safe, clear, and efficient.


    Accessing the value held by a StatusOr should be performed via operator* or operator->, after a call to ok() has verified that the value is present.

    // The same pattern used when handling a unique_ptr... std::unique_ptr foo = TryAllocateFoo(); if (foo != nullptr) foo->DoBar(); // use the value object

    // ...or an optional value... absl::optional foo = MaybeFindFoo(); if (foo.has_value()) foo->DoBar();

    // ...is also ideal for handling a StatusOr. absl::StatusOr foo = (...)

  • Tip of the Week #76: Use absl::Status

    Originally posted as TotW #76 on May 4, 2014

    By Titus Winters

    Updated 2020-02-06

    Quicklink: abseil.io/tips/76

    Some folks have questions about when and how to use absl::Status, so here are a few reasons why you ought to use Status, and some things to keep in mind when using it.

    Communicate Intent and Force the Caller to Handle Errors

    Use Status to force the caller to handle the possibility of errors. Since June 2013, a function returning an Status object cannot simply be ignored. That is, this code produces a compilation error:

    absl::Status Foo();

    void CallFoo1() Foo();

    Whereas these calls are fine:

    void CallFoo2() Foo().IgnoreError();

    void CallFoo3() if (!status.ok()) std::abort();

    void CallFoo4() absl::Status status = Foo(); if (!status.ok()) std::cerr << (...)

  • Abseil Status

    By Xiaoyi Zhang, Google Engineer, Emeritus

    The Abseil status library is now available on abseil.io. This library is used within Google for error handling and contains the following two abstractions:

    absl::Status absl::StatusOr

    Within Google, absl::Status is the primary mechanism to gracefully handle errors across API boundaries (and in particular across RPC boundaries). Some of these errors may be recoverable, but others may not. Most functions that can produce a recoverable error should be designed to return either an absl::Status (or the similar absl::StatusOr, which holds either an object of type T or an error).

    A Status can either return “OK” (represented by the enumumerated value absl::StatusCode::kOk) or one of a number of canonical error codes to indicate certain error (...)

  • Tip of the Week #5: Disappearing Act

    Originally posted as TotW #5 on June 26, 2012

    Updated 2020-06-01

    Quicklink: abseil.io/tips/5

    “Don’t know what you got till it’s gone.” –Cinderella

    Sometimes, in order to use a C++ library the right way, you need to understand both the library and the language. So … what’s wrong with the following?

    // DON’T DO THIS std::string s1, s2; ... const char* p1 = (s1 + s2).c_str(); // Avoid! const char* p2 = absl::StrCat(s1, s2).c_str(); // Avoid!

    Both (s1+s2) and absl::StrCat(s1,s2) create temporary objects (in both cases, strings, but the same rules apply for any objects). The member function c_str() returns a pointer to data that lives as long as the temporary object. How long does the temporary object live? According to the C++17 standard [class.temporary], “Temporary objects are (...)

  • Tip of the Week #140: Constants: Safe Idioms

    Originally posted as TotW #140 on December 8, 2017

    By Matt Armstrong

    Updated 2020-05-06

    Quicklink: abseil.io/tips/140

    What are best ways to express constants in C++? You probably have an idea of what the word means in English, but it is easy to express the concept incorrectly in code. Here we’ll first define a few key concepts, then get to a list of safe techniques. For the curious, we then go into more detail about what can go wrong, and describe a C++17 language feature that makes expressing constants easier.

    There is no formal definition of a “C++ constant” so let’s propose an informal one.

    The value: A value never changes; five is always five. When we want to express a constant, we need a value, but only one. The object: At each point in time an object has a value. C++ places a (...)

  • Tip of the Week #172: Designated Initializers

    Originally posted as TotW #172 on December 11, 2019

    By Aaron Jacobs

    Updated 2020-04-06

    Quicklink: abseil.io/tips/172

    Designated initializers are a syntax in the draft C++20 standard for specifying the contents of a struct in a compact yet readable and maintainable manner. Instead of the repetitive

    struct Point double x; double y; double z; ;

    Point point; point.x = 3.0; point.y = 4.0; point.z = 5.0;

    one can use designated initializers to write

    Point point = .x = 3.0, .y = 4.0, .z = 5.0, ;

    This is a little less repetitive, but more importantly, can be used in more contexts. For example, it means the struct can be made const without resorting to awkward workarounds:

    // Make it clear to the reader (of the potentially complicated larger piece of // code) that this (...)

  • Tip of the Week #173: Wrapping Arguments in Option Structs

    Originally posted as TotW #173 on December 19, 2019

    By John Bandela

    Updated 2020-04-06

    Quicklink: abseil.io/tips/173

    It came without packages, boxes or bags. And he puzzled and puzzled ‘till his puzzler was sore. Dr. Seuss

    Designated Initializers

    Designated initializers are a C++20 feature that is available in most compilers today. Designated initalizers make using option structs easier and safer since we can construct the options object in the call to the function. This results in shorter code and avoids a lot of temporary lifetime issues with option structs.

    struct PrintDoubleOptions absl::string_view prefix = “”; int precision = 8; char thousands_separator = ’,’; char decimal_separator = ’.’; bool scientific = false; ;

    void PrintDouble(double value, const (...)

  • Tip of the Week #175: Changes to Literal Constants in C++14 and C++17.

    Originally posted as TotW #175 on January 30, 2020

    By James Dennett

    Updated 2020-04-06

    Quicklink: abseil.io/tips/175

    “The only thing that stays the same is change” – Melissa Etheridge


    C++ now has some features that can make numeric literals more readable.

    Integer literals can now be written in binary (0b00101010) as well as the decimal (42), hex 0x2A and octal (052) formats that have been supported since the dawn of time.

    Single quotes (’) serve as digit separators, and can be used to group digits in numeric literals of any base (0xDEAD’C0DE).

    Floating point literals can be specified in hex (0x2A0p-4).

    Binary Literals

    Binary literals such as 0b1110’0000 can be more readable than hex (the next best option) when manipulating bit sets or working with low-level protocols. Code that (...)

  • Tip of the Week #176: Prefer Return Values to Output Parameters

    Originally posted as TotW #176 on March 12, 2020

    By Etienne Dechamps

    Updated 2020-04-06

    Quicklink: abseil.io/tips/176

    The problem

    Consider the following:

    // Extracts the foo spec and the bar spec from the provided doodad. // Returns false if the input is invalid. bool ExtractSpecs(Doodad doodad, FooSpec* foo_spec, BarSpec* bar_spec);

    Using (or implementing) this function correctly requires the developer to ask themselves a surprising number of questions:

    Are foo_spec and bar_spec out or in/out parameters? What happens to pre-existing data in foo_spec or bar_spec? Is it appended to? Is it overwritten? Does it make the function CHECK-fail? Does it make it return false? Is it undefined behavior? Can foo_spec be null? Can bar_spec? If they cannot, does a null pointer make the (...)

  • Tip of the Week #177: Assignability vs. Data Member Types

    Originally posted as TotW #177 on April 6, 2020

    By Titus Winters

    Updated 2020-04-06

    Quicklink: abseil.io/tips/177

    When implementing a type, decide on type design first. Prioritize API over implementation details. One common example of this is the tradeoff between assignability of a type vs. qualifiers for data members.

    Deciding how to represent data members

    Imagine you are writing a City class, and discussing how to represent its member variables. You know that it is short-lived, representing the city as a snapshot in time, so things like population, name, and mayor could conceivably be const - we aren’t going to use the same object in a given program for years and years, so we don’t need to account for changes in population, new census results, or elections.

    Should we have members like (...)

  • Abseil Support for CMake

    By Jon Cohen, Abseil Engineer

    CMake is a popular tool used to build multi-platform C++ projects. Abseil has had unofficial CMake support for some time, but support has never been as robust as that for Bazel. We are happy to announce that Abseil now fully supports the CMake build system.

    Abseil supports CMake through the add_subdirectory command for full source inclusion, or by local installation into your project. Future Abseil LTS releases will be supported for installation in system-wide locations (such as /usr/local, CMake’s default install location).

    We hope that this support will make it easier for users to adopt Abseil and for package managers to successfully and easily package Abseil.

    For more information on getting Abseil working with CMake, consult our CMake (...)

  • Automated Upgrade Tooling for Abseil

    By Alex Strelnikov, Abseil Engineer

    As we promised when we released our Compatibility Guidelines, we have developed a process for announcing and handling any API-breaking changes we may need to make within the Abseil code base. Our C++ Automated Upgrade guide outlines this process, which consists of clang-tidy tooling and associated communication regarding the change. A list of all such tools will be listed on our Upgrade Tools page.

    At this time, we are also releasing our first such tool: a clang-tidy check for removing bug-prone implicit conversions in calls to several absl::Duration functions.

    As outlined in our upgrade guide, we will always first serve notice of such a tool via this blog, and will also blog once we’ve officially removed the deprecated (...)

  • CppCon 2018: Modern C++ Design

    Titus Winters and Modern C++

    By Tom Manshreck, Abseil Tech Writer

    CppCon 2018 was held in Bellevue, WA at the end of September.

    C++ has changed a lot since the transformative introduction of C++11. It is now all too apparent that C++ API Design itself also needs to change as the lessons learned about, for example, type design become more understood.

    Titus Winters reflects on the changes to C++ and how the introduction of new principles such as move-only types have affected API design in this two-part talk.

    In the first part, Titus focuses on parameter passing and an API’s overload set in providing a powerful conceptual framework for API design. In the second part, we focus on the properties of well-designed types, and how to think about things like Regularity. We discuss how Regularity (...)

  • Tip of the Week #136: Unordered Containers

    Originally posted as TotW #136 on June 23, 2017

    by Matt Kulukundis

    “Sometimes, when the material is really good, you put expectations on yourself to make it the best possible show. You’re not just serving up the regular hash and doing your job and going home.” — Peter Dinklage

    Introducing absl::*_hash_map

    There is a new family of associative containers in town. They boast improvements to efficiency and provide early access to APIs from C++17. They also provide developers with direct control over their implementation and default hash functions, which is important for the long term evolution of a code base. New code should prefer these types over std::unordered_map. All of the maps and sets in this family have APIs that are nearly identical to std::unordered_map, so transitioning to them (...)

  • Tip of the Week #144: Heterogeneous Lookup in Associative Containers

    Originally posted as TotW #144 on March 23, 2018

    By Samuel Benzaquen


    Associative containers associate an element with a key. Inserting into or looking up an element from the container requires an equivalent key. In general, containers require the keys to be of a specific type, which can lead to inefficiencies at call sites that need to convert between near-equivalent types (like std::string and string_view).

    To avoid this unnecessary work, some containers provide heterogeneous lookup. This feature allows callers to pass keys of any type (as long as the user-specified comparator functor supports them). See std::map::find for an example of this feature in an STL container.

    Transparent Functors

    A transparent functor is one that accepts more than one particular type. It must (...)

  • Tip of the Week #152: AbslHashValue and You

    Originally posted as TotW #152 on June 21, 2018

    By Matt Kulukundis

    I love Mozart, but I often make a terrible hash of it. – Simon Rattle

    The absl::Hash framework is now the default hash implementation for the Swisstable family of hash tables (absl::flat,node_hash_set,map). All types hashable by this framework will automatically be useable as keys in Swisstables.

    How Do I Use It?

    Let’s say we have a simple Song struct (let’s agree that a song can be uniquely identified by these fields):

    struct Song std::string name; std::string artist; absl::Duration duration; ;

    and we want to be able to store an absl::flat_hash_set or an absl::flat_hash_map. All we have to do is add a simple friend function like:

    struct Song std::string name; std::string artist; absl::Duration duration; (...)

  • Tip of the Week #153: Don’t use using-directives

    Originally posted as TotW #153 on July 17, 2018

    by Roman Perepelitsa (roman.perepelitsa@gmail.com) and Ashley Hedberg (ahedberg@google.com)

    I view using-directives as time-bombs, both for the parties that deal in them and the language system. – Ashley Hedberg with apologies to Warren Buffett


    Using-directives (using namespace foo) are dangerous enough to be banned by the Google style guide. Don’t use them in code that will ever need to be upgraded.

    These are not to be confused with using-declarations (using ::foo::SomeName), which are permitted in *.cc files.

    Using-directives at Function Scope

    What do you think this code does?

    namespace totw namespace example namespace

    TEST(MyTest, UsesUsingDirectives) using namespace ::testing; Sequence seq; // ::testing::Sequence (...)

  • Civil Time in Abseil

    By Greg Miller, Bradley White, and Shaindel Schwartz

    Almost every spring and fall there are news headlines about software that misbehaved during a daylight-saving transition. In much of the world, DST transitions occur multiple times per year, yet it is still a veritable minefield of latent bugs due to the complexities inherent in reasoning about civil-time discontinuities. To avoid these problems, a civil-time library must present the programmer with a correct — yet simplified — model that makes expressing the desired intent easy and writing bugs more obvious.

    To that end, we are very pleased to introduce a new feature for the Abseil time library — civil time support. This update adds a set of constructs and functions that are used to represent and perform computations with civil times. (...)

  • Abseil Python Docs are Here!

    By Junjay Tan

    Abseil Python now includes a documentation set on abseil.io!

    Abseil Python provides various libraries for building Python applications. This code is collected from Google’s internal Python code base and has been extensively tested and used in production. They provide features for application startup, distributed command line flags, custom logging, and testing.

    Until now, the only documentation for Abseil Python has been in the source code. This was comprehensive but did not always provide information for new users in an easy-to-read format.

    We’re happy to announce an Abseil Python Quickstart Guide and module-specific programming guides similar to those for Abseil C++. These guides are patterned after those used internally at Google to onboard new Googlers (nooglers), and (...)

  • Clang-Tidy Checks for Abseil

    By Deanna Garcia and Hugo Gonzalez, Abseil Interns

    Abseil wants to help developers avoid common mistakes unique to our collection of libraries. Therefore, we have developed a set of clang-tidy checks for Abseil, allowing you to catch these errors early on before they become bigger problems.

    Clang-Tidy) is a useful tool to help developers write C++ code in a correct and efficient manner. Clang-Tidy now supports a set of Abseil checks designed to diagnose and fix typical programming errors specific to Abseil including:

    Compatibility guideline violations Style violations Interface misuse Bugs that can be deduced via static analysis

    We hope that these checks will help projects that depend on Abseil have high standards of code quality.

    Our checks can be found on llvm’s (...)

  • Coroutine Types

    By Titus Winters

    The first hint of standard library design that takes advantage of coroutines (P1056) came through the Library Evolution Working Group (LEWG, responsible for design for the C++ standard library) during the Rapperswil meeting this summer. It was … surprising. As much as I want coroutines in the language, the design smell here was disconcerting. I want to point out what LEWG saw before we commit to this direction irrevocably - coroutine types as currently designed are baffling.


    Coroutines are an important new language feature for C++, but also a very old idea. In its current incarnation, the major force behind Coroutines in C++ is Gor Nishanov (whom I absolutely love working with). If you aren’t familiar with the history, or want a refresher on how (...)

  • The Abseil str_format Library

    By Juemin Yang, Abseil Engineer

    Abseil now includes a type-safe string formatting library: str_format. The str_format library is a typesafe replacement for the family of printf() string formatting routines within the standard library header. The str_format library provides most of the functionality of printf() type string formatting and a number of additional benefits:

    Type safety, including native support for std::string and absl::string_view Reliable behavior independent of standard libraries Support for the POSIX positional extensions Much faster (generally 2 to 3 times faster) than native printf functions Streamable to a variety of existing sinks

    For more information, consult Abseil’s StrFormat Guide If you are interested in the design of this library, check out our (...)