Skip to content

NRVO not performed in template function with auto return type #38674

@wjakob

Description

@wjakob
mannequin
Bugzilla Link 39326
Version 7.0
OS All
CC @dwblaikie,@gergol,@zygoloid

Extended Description

I've run into the following rather bizarre bug on Clang that appears to be a standard violation: when a function template has an auto return value, return value optimization (RVO) no longer works. Everything is okay for non-template functions and functions with an explicitly specified return value type.

Consider the following piece of code that reproduces this issue:

#include <stdio.h>

struct A {
    A() { printf("A::A()\n"); }
    A(const A&) { printf("A::A(const A&)\n"); }
    A(A&&) { printf("A::A(A&&)\n"); }
    ~A() { printf("A::~A()\n"); }
    A& operator=(const A&) { printf("A::operator=(const A&)\n"); return *this; }
    A& operator=(A&&) { printf("A::operator=(A&&)\n"); return *this;}
};

A test1(int z) { A x; return x; }

auto test2(int z) { A x; return x; }

template <typename T> A test3(T z) { A x; return x; }

template <typename T> auto test4(T z) { A x; return x; } /// <- problem!

int main(int argc, char *argv[]) {
    printf("\n-- Test 1:\n");
    test1(1);
    printf("\n-- Test 2:\n");
    test2(1);
    printf("\n-- Test 3:\n");
    test3(1);
    printf("\n-- Test 4:\n");
    test4(1);
    return 0;
}

This produces the following output:

$ clang++ test.cpp -o test -std=c++14
$ ./test
-- Test 1:
A::A()
A::~A()

-- Test 2:
A::A()
A::~A()

-- Test 3:
A::A()
A::~A()

-- Test 4:
A::A()
A::A(A&&)
A::~A()
A::~A()

Comparison (GCC 8):

-- Test 1:
A::A()
A::~A()

-- Test 2:
A::A()
A::~A()

-- Test 3:
A::A()
A::~A()

-- Test 4:
A::A()
A::~A()

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugzillaIssues migrated from bugzillac++14clang:frontendLanguage frontend issues, e.g. anything involving "Sema"confirmedVerified by a second partymissed-optimization

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions