我正在学习指针、引用、返回值和三元运算符。
我正在尝试通过使用参数 int *&A
为动态数组正确使用指向引用的指针,而不返回一个新创建的数组。我非常想从主循环中复制数组,并设置大小,如果分配失败则抛出错误。
这是解决这个问题的正确方法吗:
int
*_resize(int *&A, int s)
{
try {
return A = new int[s] == (nullptr) ? throw std::bad_alloc() : A;
} catch (...) {
std::cout << "H" << std::endl;
}
}
int main()
{
int *A;
A = _resize (A, 1000000005546456456ul); // Test
}
我还应该使用 (std::nothrow)
吗:
return A = new (std::nothrow) int[s]
最佳答案
为什么不简单呢?:
#include <iostream>
int *allocate(int s) noexcept
try { return new int[s]; }
catch (...) { std::cout << "H" << std::endl; return nullptr; }
int main() {
int *A = allocate (10000);
//(printing from utility functions and not using RAII
//aren't exactly the C++ way)
}
用以下划线和下划线开头的函数命名是未定义的行为。
传递 1000000005546456456ul 将以实现定义的方式转换为 int
,可能转换为 -235129464
,然后将转换为非常大的 std::size_t
(可能是 4059837832 或 18446744073474422152)。不确定这是否是您想要的。
关于c++ - 三元运算符的动态指针引用数组返回值异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56615217/