C++ 为什么断言在这里不起作用?

C++ 为什么断言在这里不起作用?,c++,r,rcpp,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();

代码如下:

#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);
}

对于g++使用-g启用调试选项:

g++ -g code.cpp
或Visual Studio中的调试模式。

请注意,
assert()
等明确禁止用于CRAN上载。引用该页的内容:

包中提供的代码和示例不应该做任何事情 这可能被认为是恶意的或反社会的。以下是 来自过去经验的说明性例子

  • 编译后的代码永远不应该终止运行它的R进程。因此,C/C++调用
    断言
    /
    中止
    /
    退出
    ,Fortran调用 必须避免停止等操作。R代码也不能调用
    q()

因此,关于调试模式的答案在技术上是正确的,但也请注意,如果您计划在某个时候上载CRAN,则不应使用此选项。

问题通过使用
抛出
而不是
断言
,Rcpp实际上会将内容放入适当的try-catch块中,这非常好

#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();
    Rcout << nx << '\n' << ny << std::endl;

    if(nx != ny) {
        throw std::invalid_argument("Two vectors are not of the same length!");
    }

    double dist=0;
    for(int i = 0; i < nx; i++) {
        dist += pow(x[i] - y[i], 2);
    }

    return sqrt(dist);
}
#包括
#包括
#包括
#包括
使用名称空间Rcpp;
//[[Rcpp::导出]]
双eudist(数值向量x,数值向量y){
int nx=x.size();
int ny=y.size();

Rcout您是如何编译的?
assert
如果您定义了
NDEBUG
,预处理器将删除它;这可能就是正在发生的事情。为切换到
throw()而欢呼三声,并向上投票
Oh,要成为一个坚持者:使用
Rcpp::Rcout
而不是
std::cout
来写入R的i/o缓冲区。此外,您应该创建一个新的答案,而不是用答案编辑您自己的问题。
#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();
    Rcout << nx << '\n' << ny << std::endl;

    if(nx != ny) {
        throw std::invalid_argument("Two vectors are not of the same length!");
    }

    double dist=0;
    for(int i = 0; i < nx; i++) {
        dist += pow(x[i] - y[i], 2);
    }

    return sqrt(dist);
}