测试指针
test a pointer
我正在编写一个返回double*
的方法。但是,我想将另一个方法行为基于此方法的输出。我想要拥有
if (methodReturningArray()==0)
{
this_behavior();
}
else
{
this_other_behavior(methodReturningArray());
}
那么让methodReturningArray()
返回"初始化"或"构建"double*
是否合适,如果无法正确初始化或构建此double*
,则像那样返回
double* new_array ;
return new_array ;
?
换句话说,double*
输出还扮演布尔值的角色,以检查某些属性是否已完成,以便可以生成double*
输出。
谢谢和问候。
要指示通过指针返回的内容尚未初始化,请使用 return NULL
。并用if(double* d = method())
(或您喜欢的任何其他方式(检查它。
但是,这不是你(或我(祖父C++,你应该只写这样的东西,当你绝对有理由这样做的时候。我宁愿按包装的值返回std::array
或std::vector
,如果导致初始化失败的行为异常,则引发异常。如果初始化失败是想法的一部分,我会将返回值包装在boost::optional
中。但也许我会写一些需要OutputIterator
的东西来不在我的客户端上强制任何特定的容器。
灾难注意事项:double* d; return d
会给客户端留下一个指向随机内存的指针。她没有办法弄清楚是否必须deleted[]
或是否有效。始终初始化指针。
代码片段:
// outputiterator
template<typename OutputIterator>
void myFunc(OutputIterator o) {
// fill stuff in
if(someThing) {
for(int i = 0; i < 5; ++i)
{
*o++ = 23;
}
} else {
// leave it empty
}
}
// client calls like:
std::vector<double> v;
myFunc(std::back_inserter(v));
if(!v.empty()) {
} else {
}
// exception
std::vector<double> myFunc() {
std::vector<double> v;
if(someThing) { v.push_back(23); return v; }
else throw std::runtime_error("Nargh!");
}
// client
try {
auto v = myFunc();
} catch(std::runtime_error err) {
}
// optional
boost::optional<std::vector<double>>
myFunc() {
std::vector<double> v;
if(someThing) { v.push_back(23); return v; }
else return boost::optional< std::vector<double> >();
}
//client
auto v = myFunc();
if(v) {
} else {
}
基本上
你有三种方法。
1( 出错时,返回 NULL。然后,您可以毫无问题地进行布尔检查,
在大多数情况下就足够了。2( 返回布尔值,并使用引用或指针参数处理 double* 输出,如下所示:
bool methodReturningArray(double **out) { *out = ...; return true; }
double *out;
if (!methodReturningArray(&out)) this_other_behavior(out); else ....
3(抛出一个异常 - IMO有点复杂且无用。
返回未初始化的指针将不允许你对它进行布尔计算,这很危险,因为这样的指针之后会被假定为悬空指针。
相关文章:
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- 谷歌测试比较指针数组的内容
- Qt单元测试:指针列表上的QCOMPARE函数
- 测试此指针的常量指针性质
- 使用 SFINAE 测试是否可以将一个指针类型static_cast到另一个指针类型
- 测试原始指针 c++,但找不到泄漏
- 如何测试指针类型是否可以安全地转换为另一种指针类型?
- 在测试中使用unique_ptr时指针错误无效
- (指针)降低测试分数后计算平均功能的问题
- 为什么EXPECT_CALL测试在使用取消引用的指针时意外通过
- 如何测试 TCHAR 指针是否已初始化
- 测试指针是否为null的最有效方法是什么?
- 在Google测试固定装置中使用参考代替指针
- 在链接列表中测试指针
- 测试指针以进行零并比较偏移的值
- 测试C++对象的有效性,就好像它是一个指针一样
- 使用字符指针测试条件
- 测试类型是否为(智能)指针的通用方法
- 级联结构指针测试代码中的分段错误
- while循环中的智能指针测试:使用逗号运算符