从可能引发异常的函数返回 std::string
Returning a std::string from a function that might throw an exception
我在Java中做了很多...
String something = "A default value.";
try {
something = this.aFunctionThatMightThrowAnException();
} catch (Exception ignore) { }
this.useTheString(something);
现在我正在尝试为std::string
找到一种等效的方法。 这是我所拥有的...
std::string something("A defualt value.");
try {
something = this->aFunctionThatMightThrowAnException();
} catch (const std::exception& ignore) { }
this->useTheString(something);
为了完整起见,以下是aFunctionThatMightThrowAnException()
可能的样子...
std::string MyClass::aFunctionThatMightThrowAnException() {
/* Some code that might throw an std::exception. */
std::string aString("Not the default.");
return aString;
}
关于C++版本,我有三个问题:
- 这是解决此类问题的公认方法吗? 还是将
something
传递给aFunction
作为参考更常见? - 我从
aFunction...
返回的something
作业安全吗? 具体来说,最初分配给"A default value."
的内存是否已发布?
在 - 引发异常的情况下,是否有我看不到的副作用?
这是解决此类问题的公认方法吗?
是的。
还是将某些东西传递给 aFunction 作为引用更常见?
不。
我的分配是作为函数的回报...安全?具体来说,最初分配给"默认值"的内存是否释放?
是的。
在引发异常的情况下,是否有我看不到的副作用?
不。
相关文章:
- 从函数返回const char*数组
- 检查函数返回类型是否与STL容器类型值相同
- 从 c 或 cpp 系列子函数返回到主函数
- 从函数返回任意简单类型的数据
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 从 C++ 中的函数返回数组地址问题
- VirtDisk.h QueryChangesVirtualDisk() 函数返回 RangeCount 为 0
- 为什么glGetSubroutineIndex为不同的函数返回相同的值?
- 在 c++ 中将函数返回类型指定为模板参数
- 从封装在对象中的函数 C++ 返回时为空的列表
- 为什么向量内部的指针在从函数返回时会发生变化?
- 函数返回的 rvalue 引用(表达式)是 xvalue - 但没有标识?
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 寿命延长从函数返回引用
- 程序不向函数返回值
- 字符串函数返回奇怪的值
- 类的大问题,以及从空函数c++返回
- 为什么在尝试测量函数返回所需的时间时,我的运行时编号是错误的?
- C++二叉搜索树模板从函数返回节点
- NVCC 错误:string_view.h:constexpr 函数返回是非常量