3

My colleague and I are developing with an updated GCC 8.2 compiler. Previously had been using GCC 4.8 with -std=c++11. I was surprised to find that with GCC 8.2 a unique_ptr is automatically transferred to a shared_ptr. See this minimal example:

#include <iostream>
#include <memory>

using namespace std;

shared_ptr<int>
getMeAnInt()
{
    auto ret = unique_ptr<int>(new int(32));
    return ret;
}


int main()
{
    auto i = getMeAnInt();

    cout << *i << endl;
}

Using GCC 4.8, this fails to compile because an explicit std::move is needed when returning ret to transfer the unique_ptr to a shared_ptr. In GCC 8.2 this compiles and works fine.

Failure with GCC 4.8: https://godbolt.org/z/I4g9dI

Same code, but success with GCC 8.2: https://godbolt.org/z/ZeDajS

I assume this is an intentional change, but can someone explain to me the reasoning behind the change? Up until now I had run under the assumption that the explicit std::move requirement was a valuable compiler enforcement to make explicit that ownership was being transferred.

firebush
  • 5,180
  • 4
  • 34
  • 45

0 Answers0