c – 为什么断言不起作用?
作者:互联网
这是代码:
#include <Rcpp.h>
#include <iostream>
#include <assert.h>
#include <stdio.h>
using namespace Rcpp;
// [[Rcpp::export]]
double eudist(NumericVector x, NumericVector y) {
int nx = x.size();
int ny = y.size();
std::cout << nx << '\n' << ny << std::endl;
assert(nx == ny);
double dist=0;
for(int i = 0; i < nx; i++) {
dist += pow(x[i] - y[i], 2);
}
return sqrt(dist);
}
在将其获取到R之后,我得到以下结果,显然在出现错误时它不会中止:
#////////////////////////////////////////////////////
sourceCpp('x.cpp')
#////////////////////////////////////////////////////
eudist(c(0, 0), c(1, 1))
2
2
[1] 1.4142
#////////////////////////////////////////////////////
eudist(c(0, 0), c(1, 1, 1))
2
3
[1] 1.4142
解决方法:
请注意,对于CRAN上载,明确禁止使用assert()等.从CRAN Repo Policy页面引用:
The code and examples provided in a package should never do anything
which might be regarded as malicious or anti-social. The following are
illustrative examples from past experience.
- Compiled code should never terminate the R process within which it is running. Thus C/C++ calls to
assert
/abort
/exit
, Fortran calls to
STOP
and so on must be avoided. Nor may R code callq()
.
所以关于调试模式的答案在技术上是正确的,但是请注意,如果您打算在某个时候上传CRAN,则不应该使用它.
标签:c,r,rcpp 来源: https://codeday.me/bug/20191006/1862684.html