测试指针

test a pointer

本文关键字:指针 测试      更新时间:2023-10-16

我正在编写一个返回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::arraystd::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有点复杂且无用。

返回未初始化的指针将不允许你对它进行布尔计算,这很危险,因为这样的指针之后会被假定为悬空指针。