Consider the following (to be compiled with C++14)
#include <iostream>
#include <vector>
// Foo adds an element to a std::vector passed by reference
// on construction in the destructor
struct Foo {
Foo(std::vector<double>& v) : m_v(v){
}
~Foo(){
m_v.push_back(1.0);
}
std::vector<double>& m_v;
};
std::vector<double> bar(){
std::vector<double> ret;
Foo foo(ret);
return ret;
}
int main(){
std::cout << bar().size() << "\n";
}
In gcc8.3 the output is 1, which means that foos destructor has an effect on the returned vector.
In MSVC14.1 the output is 0. You can force the output to be the same as gcc8.3 by replacing the line Foo foo(ret); with {Foo foo(ret);} (i.e. by forcing the scope).
I don't think this is dangling reference undefined behaviour (because ret is declared before foo) but rather that this could be a bug in MSVC14.1 (and I will create a bug report if so). Does anyone know for sure?