是否可以在C++中动态分配一个临时变量
Is it possible to dynamically allocate a temporary variable in C++?
是否可以在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;
}
相关文章:
- 用C++中的一个变量定义一个常量
- 一个变量的输入值也会保存到另一个变量中
- 将双精度变量设置为另一个变量的值
- 对具有相同方法的不同类使用一个变量
- 为什么一个变量获得与另一个值相同的值
- 尝试在 C++ 中为 ifstream 提供一个变量
- 类中的一个变量显示,但另一个不显示
- 声明一个变量,该变量在 c++ 或 c 中具有值,当程序终止时不会被销毁
- c++问题:给一个变量赋值后,另一个变量发生了变化
- 如何将一个变量用于父类和派生类
- 如何在循环中使用scanf,将值存储到一个变量中,然后打印出来?
- 我如何将一个变量与另一个变量进行比较,例如我想如果(var1 > var2 x 1),然后执行此 c++
- 如何在一个函数中定义一个变量,并在另一个函数中访问和更改它?(C++)
- 如果一个变量在它之前释放了另一个(相同的数据类型)变量,如何将其分配给内存?
- 迭代器或反向器的一个变量
- fstream库,试图创建一个变量名为(c++)的文件
- 如何在 c++ 中将两个不同类型的变量分配给一个变量
- 如何将一些变量放在一个变量中?
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 如何用索引命名一个变量来存储输入 mxArray?