Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

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

<p>&nbsp;</p> <quillbot-extension-portal></quillbot-extension-portal>

April 12, 2019
Marek Polacek
Related products:
Developer Toolset

    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

    • Federated identity across the hybrid cloud using zero trust workload identity manager

    • Confidential virtual machine storage attack scenarios

    • Introducing virtualization platform autopilot

    • Integrate zero trust workload identity manager with Red Hat OpenShift GitOps

    • Best Practice Configuration and Tuning for Linux and Windows VMs

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    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
    © 2026 Red Hat

    Red Hat legal and privacy links

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

    Chat Support

    Please log in with your Red Hat account to access chat support.