Is it possible to dynamically allocate a temporary variable in C++ ?
I want to do something like that :
#include <iostream> #include <string> std::string* foo() { std::string ret("foo"); return new std::string(ret); } int main() { std::string *str = foo(); std::cout << *str << std::endl; return 0; } This code works but the problem is I have to create an other string in order to return it as a pointer. Is there a way to put my temporary/local variable inside my heap without recreate an other object ?
Here is an illustration of how I would do that :
std::string* foo() { std::string ret("foo"); return new ret; // This code doesn't work, it is just an illustration }
std::string foo() { return "foo"; }? The copy is all but guaranteed to be elided.