为什么断言不起作用?

qed*_*qed 6 c++ r rcpp

这是代码:

#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);
}
Run Code Online (Sandbox Code Playgroud)

在将其获取到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
Run Code Online (Sandbox Code Playgroud)

Dir*_*tel 4

请注意,assert()CRAN上传明确禁止等.从CRAN Repo Policy页面引用:

软件包中提供的代码和示例绝不应该做任何可能被视为恶意或反社交的事情.以下是过去经验的说明性示例.

  • 编译代码永远不应该终止运行它的R进程.因此必须避免对assert/ abort/ exit,Fortran调用等进行 C/C++调用STOP.R代码也不能打电话q().

所以关于调试模式的答案在技术上是正确的,但是请注意,如果您打算在某个时候上传CRAN,则不应该使用它.