c++c++11g++4.8

Tuple as a return type, are unaccessed values optimized out?


I'm returning three items from a function in the form of a std::tuple.

... myFunction()
{
    ...
    return std::tuple< int, unsigned long long, unsigned int >{ errorCode, timeStamp, sizeOfBuffer };
}

Since return values have to be accessed using std::get or std::tie, does the compiler optimize for unused values (g++ 4.8)?


Solution

  • Yes, it can

    #include "stdio.h"
    #include <tuple>
    
    std::tuple<int, unsigned long long, unsigned int> myFunction()
    {
        return std::tuple<int, unsigned long long, unsigned int>{ 1, 2, 3 };
    }
    
    int f()
    {
      return std::get<0>(myFunction());
    }
    

    Becomes

    myFunction():
        movq    %rdi, %rax
        movl    $3, (%rdi)
        movq    $2, 8(%rdi)
        movl    $1, 16(%rdi)
        ret
    f():
        movl    $1, %eax
        ret