I'm new to c++ and would like to know if there is a way to create an object in a function and then return that object without it having to be copied in memory. I know the original local object goes out of scope, but I hoped the compiler could optimize it in a way that the copy of the object would just reuse the same memory adress.
int foo()
{
int bar = 5;
std::cout << &bar << std::endl;
return bar;
}
int main()
{
char a;
auto b = foo();
std::cout << &b << std::endl;
std::cin >> a;
return 0;
}
This returns different memory addresses. Since the address of bar is no longer needed and b is always the same size, is there any reason it couldn't just use the same address and save the step of copying?
It doesn't really matter for a simple integer but for larger Objects, what would be the preferred way to make sure the returned object does not get copied in memory?
Would the following be a good approach?
int & foo(int & bar)
{
std::cout << &bar << std::endl;
// do things with bar
return bar;
}
int main()
{
char a;
auto bar = 5;
auto & b = foo(bar);
std::cout << &b << std::endl;
std::cin >> a;
return 0;
}
As a side question, why does the following thing work:
int & foo()
{
int bar = 5;
std::cout << &bar << std::endl;
return bar;
}
int main()
{
char a;
auto & b = foo();
std::cout << &b << " " << b << std::endl;
std::cin >> a;
return 0;
}
I expected that bar is out of scope and could no longer be referred to, but this compiles and returns the correct value (MSVC++ 2013).