代码如下:
#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
最佳答案
请注意,assert()
等被明确禁止用于 CRAN 上传。引用自 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 toSTOP
and so on must be avoided. Nor may R code callq()
.
所以关于 Debug模式的答案在技术上是正确的,但也请注意,如果您计划在某个时候上传 CRAN,则不应该使用它。
关于c++ - 为什么断言在这里不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21409237/