我可以清除外部声明的数组以供进一步使用吗?

时间:2018-02-17 21:10:26

标签: c++ arrays variables delete-operator

我有一个声明# install.packages("gridExtra") require(gridExtra) # also loads grid require(lattice) x <- seq(pi/4, 5 * pi, length.out = 100) y <- seq(pi/4, 5 * pi, length.out = 100) r <- as.vector(sqrt(outer(x^2, y^2, "+"))) grid <- expand.grid(x=x, y=y) grid$z <- cos(r^2) * exp(-r/(pi^3)) plot1 <- levelplot(z~x*y, grid, cuts = 50, scales=list(log="e"), xlab="", ylab="", main="Weird Function", sub="with log scales", colorkey = FALSE, region = TRUE) plot2 <- levelplot(z~x*y, grid, cuts = 50, scales=list(log="e"), xlab="", ylab="", main="Weird Function", sub="with log scales", colorkey = FALSE, region = TRUE) plot3 <- levelplot(z~x*y, grid, cuts = 50, scales=list(log="e"), xlab="", ylab="", main="Weird Function", sub="with log scales", colorkey = FALSE, region = TRUE) plot4 <- levelplot(z~x*y, grid, cuts = 50, scales=list(log="e"), xlab="", ylab="", main="Weird Function", sub="with log scales", colorkey = FALSE, region = TRUE) plot5 <- levelplot(z~x*y, grid, cuts = 50, scales=list(log="e"), xlab="", ylab="", main="Weird Function", sub="with log scales", colorkey = FALSE, region = TRUE) plot6 <- levelplot(z~x*y, grid, cuts = 50, scales=list(log="e"), xlab="", ylab="", main="Weird Function", sub="with log scales", colorkey = FALSE, region = TRUE) plot7 <- levelplot(z~x*y, grid, cuts = 50, scales=list(log="e"), xlab="", ylab="", main="Weird Function", sub="with log scales", colorkey = FALSE, region = TRUE) plot8 <- levelplot(z~x*y, grid, cuts = 50, scales=list(log="e"), xlab="", ylab="", main="Weird Function", sub="with log scales", colorkey = FALSE, region = TRUE) plot9 <- levelplot(z~x*y, grid, cuts = 50, scales=list(log="e"), xlab="", ylab="", main="Weird Function", sub="with log scales", colorkey = FALSE, region = TRUE) a <- c(plot1, plot2,plot3,plot4,plot5,plot6,plot7,plot8,plot9, layout = c(3, 3)) update(a,strip = strip.custom(factor.levels = c("1","2","3","4","5","6","7","8","9"), par.strip.text=list(cex=1.0),bg=list(col="gray95")))][1]][1] 的.h文件。在我的主.cpp文件中,在我初始化extern Obj *objArr;的任何函数之外。在我的main()函数中,我连续两次调用函数Obj *objArr;,每次都有不同的参数。

最终,我需要在不同的.cpp文件中访问objArr。这将在使用runSim()第一行中的大小初始化后发生。希望我可以清除objArr的内容并分配大小而不实际删除外部变量,以便在下次调用runSim()时可以使用不同的大小和内容重新创建它。这个runSim(int size)行真的会实现我的目标吗?

delete[]objArr

谢谢

1 个答案:

答案 0 :(得分:0)

使用

void runSim(int size) {
    objArr = new Obj[size];
    //some things are done
    delete[]objArr;
}

技术上是正确的,但它的设计很糟糕。

如果要在函数中分配释放对象的内存,在函数范围内使用std::vector将会更加清晰。

void runSim(int size) {
    std::vector<Obj> objArr(size);

    //some things are done

    // No need for this
    // delete[]objArr;
}

如果//some things are done的一部分涉及在另一个中使用objArr,只需将对象传递给需要它的函数即可。假设您使用:

void runSim(int size) {
    objArr = new Obj[size];
    foo();
    delete[]objArr;
}

foo使用objArr。将foo更改为期望std::vector<Obj>&std::vector<Obj> const&作为参数,而不是依赖于全局变量。

void runSim(int size) {
    std::vector<Obj> objArr(size);
    foo(objArr);
}