I have discovered an interesting problem that I am unsure of the reason. Here is my code:
#include<vector>
#include<iostream>
using namespace std;
std::vector<int>&& fun_1()
{
std::vector<int> v{ 1, 2, 3 };
return std::move(v);
}
std::vector<int>&& fun_2()
{
std::vector<int> v(3, 2);
return std::move(v);
}
int main() {
//std::vector<int> v1 = fun_1();
std::vector<int> v2 = fun_2(); //why isn't move-constructor called?
//out << v1.data() << endl;//0x00
cout << v2.data() << endl;//0x00
}
I have two questions.
Firstly, why are v1.data() and v2.data() both returning a zero pointer? I had expected the move constructor of std::vector<int> to be called, but it seems like it wasn't.
Secondly, when I uncomment the first line in the main function, a memory error is raised when the function exits. It appears to be occurring during the deletion of some object related to v1. I am working in the Visual Studio 2022 environment.
Could someone please explain both issues to me?
fun_2to which object do you think the returned reference refers? Do you think that this object is still alive when you use the reference to initializev2? (And the same applies tofun_1/v1.)return std::move(v);would not optimize anything. Just return the vector and return value optimization will do the rest.data? I didnt find anything like that. After moving from it it is empty,begin == end, butdatacould be anything afaik