Skip to main content
Redhat Developers  Logo
  • Products

    Platforms

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat AI
      Red Hat AI
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • View All Red Hat Products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat Developer Hub
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat OpenShift Local
    • Red Hat Developer Sandbox

      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Secure Development & Architectures

      • Security
      • Secure coding
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • Product Documentation
    • API Catalog
    • Legacy Documentation
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Understanding when not to std::move in C++

 

April 12, 2019
Marek Polacek
Related products:
Developer Tools

Share:

    One of the most important concepts introduced in C++11 was move semantics. Move semantics is a way to avoid expensive deep copy operations and replace them with cheaper move operations. Essentially, you can think of it as turning a deep copy into a shallow copy.

    Move semantics came along with several more or less related features, such as rvalue references, xvalues, forwarding  references, perfect forwarding, and so on. The standard C++ library gained a function template called std::move, which, despite its name, does not move anything. std::move merely casts its argument to an rvalue reference to allow moving it, but doesn't guarantee a move operation. For example, we can write a more effective version of swap using std::move:

    template<typename T>
    void swap(T& a, T& b)
    {
      T t(std::move (a));
      a = std::move (b);
      b = std::move (t);
    }

    This version of swap consists of one move construction and two move assignments and does not involve any deep copies. All is well. However, std::move must be used judiciously; using it blithely may lead to performance degradation, or simply be redundant, affecting readability of the code. Fortunately, the compiler can sometimes help with finding such wrong uses of std::move. In this article, I will introduce two new warnings I've implemented for GCC 9 that deal with incorrect usage of std::move.

    -Wpessimizing-move

    When returning a local variable of the same class type as the function return type, the compiler is free to omit any copying or moving (i.e., perform copy/move elision), if the variable we are returning is a non-volatile automatic object and is not a function parameter. In such a case, the compiler can construct the object directly in its final destination (i.e., in the caller's stack frame). The compiler is free to perform this optimization even when the move/copy construction has side effects. Additionally, C++17 says that copy elision is mandatory in certain situations. This is what we call Named Return Value Optimization (NRVO). (Note that this optimization does not depend on any of the -O levels.) For instance:

    struct T {
      // ...
    };
    
    T fn()
    {
      T t;
      return t;
    }
    
    T t = fn ();

    The object a function returns doesn't need to have a name. For example, the return statement in the function fn above might be return T(); and copy elision would still apply. In this case, this optimization is simply Return Value Optimization (RVO).

    Some programmers might be tempted to "optimize" the code by putting std::move into the return statement like this:

    T fn()
    {
      T t;
      return std::move (t);
    }

    However, here the call to std::move precludes the NRVO, because it breaks the conditions specified in the C++ standard, namely [class.copy.elision]: the returned expression must be a name. The reason for this is that std::move returns a reference, and in general, the compiler can't know to what object the function returns a reference to. So GCC 9 will issue a warning (when -Wall is in effect):

    t.C:8:20: warning: moving a local object in a return statement prevents copy elision [-Wpessimizing-move]
    8 | return std::move (t);
      |        ~~~~~~~~~~^~~
    t.C:8:20: note: remove ‘std::move’ call

    -Wredundant-move

    When the class object that a function returns is a function parameter, copy elision is not possible. However, when all the other conditions for the RVO are satisfied, C++ (as per the resolution of Core Issue 1148) says that a move operation should be used: overload resolution is performed as if the object were an rvalue (this is known as two-stage overload resolution). The parameter is an lvalue (because it has a name), but it's about to be destroyed. Thus, the compiler ought to treat is as an rvalue.

    For instance:

    struct T {
      T(const T&) = delete;
      T(T&&);
    };
    
    T fn(T t)
    {
      return t; // move used implicitly
    }

    Explicitly using return std::move (t); here would not be pessimizing—a move would be used in any case—it is merely redundant. The compiler can now point that out using the new warning -Wredundant-move, enabled by -Wextra:

    r.C:8:21: warning: redundant move in return statement [-Wredundant-move]
    8 | return std::move(t); // move used implicitly
      |        ~~~~~~~~~^~~
    r.C:8:21: note: remove ‘std::move’ call

    Because the GNU C++ compiler implements Core Issue 1579, the following call to std::move is also redundant:

    struct U { };
    struct T { operator U(); };
    
    U f()
    {
      T t;
      return std::move (t);
    }
    

    Copy elision isn't possible here because the types T and U don't match. But, the rules for the implicit rvalue treatment are less strict than the rules for the RVO, and the call to std::move is not necessary.

    There are situations where returning std::move (expr) makes sense, however. The rules for the implicit move require that the selected constructor take an rvalue reference to the returned object's type. Sometimes that isn't the case. For example, when a function returns an object whose type is a class derived from the class type the function returns. In that case, overload resolution is performed a second time, this time treating the object as an lvalue:

    struct U { };
    struct T : U { };
    
    U f()
    {
      T t;
      return std::move (t);
    }
    

    While in general std::move is a great addition to the language, it's not always appropriate to use it, and, sadly, the rules are fairly complicated. Fortunately, the compiler is able to recognize the contexts where a call to std::move would either prevent elision of a move or a copy—or would actually not make a difference—and warns appropriately. Therefore, we recommend enabling these warnings and perhaps adjusting the code base. The reward may be a minor performance gain and cleaner code. GCC 9 will be part of Fedora 30, but you can try it right now on Godbolt.

    Last updated: February 6, 2024

    Recent Posts

    • Staying ahead of artificial intelligence threats

    • Strengthen privacy and security with encrypted DNS in RHEL

    • How to enable Ansible Lightspeed intelligent assistant

    • Why some agentic AI developers are moving code from Python to Rust

    • Confidential VMs: The core of confidential containers

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2025 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue