是否可以在C++中动态分配一个临时变量

Is it possible to dynamically allocate a temporary variable in C++?

本文关键字:一个 变量 C++ 动态分配 是否      更新时间:2023-10-16

是否可以在C++中动态分配临时变量?
我想做这样的事情:

#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;
}

这段代码有效,但问题是我必须创建另一个字符串才能将其作为指针返回。有没有一种方法可以在不重新创建其他对象的情况下将临时/本地变量放入堆中?
以下是我将如何做到这一点的示例:

std::string* foo()
{
  std::string ret("foo");
  return new ret; // This code doesn't work, it is just an illustration
}

是的,它被称为智能指针:

#include <memory>
std::unique_ptr<std::string> foo()
{
    return std::unique_ptr<std::string>("foo");
}
// Use like this:
using namespace std;
auto s = foo();     // unique_ptr<string> instead of auto if you have an old standard.
cout << *s << endl; // the content pointed to by 's' will be destroyed automatically
                    // when you stop using it

编辑:不更改返回类型:

std::string* foo()
{
    auto s = std::unique_ptr<std::string>("foo");
    // do a lot of stuff that may throw
    return s.release(); // decorellate the string object and the smart pointer, return a pointer
                        // to the string
}

这个怎么样:

std::string* foo()
{
    std::string * ret = new std::string("foo");
    // do stuff with ret
    return ret;
}