【问题标题】:Why is there no output for this code and also how to reclaim memory?为什么这段代码没有输出以及如何回收内存?
【发布时间】:2021-03-13 23:39:33
【问题描述】:

This is the original lab question

#include <iostream>
#include <vector>
#include <new>
using namespace std;

class c{
public:
    c(){
    int i = 0;

    vector <c*> objects;
    while (true){

        objects.push_back(new c());
        cout << "Object " << i+1 << "is created.";
        i++;

        if (i == 10) {
            throw i+1;}}}
};

int main(){

    while (true){
    try {c obj;}

    catch (int x) {cout << "Object" << x << "cannot be created as only 10 objects are allowed";}}

    return 0;
}

这就是我所做的。 我有两个问题。

1.为什么它不打印任何输出?

2。如何添加回收此内存的静态成员函数?

这是 c++,在此先感谢。

【问题讨论】:

  • 任务说你应该实现一个 operator new 而不是把所有东西都放在构造函数中

标签: c++ exception memory static output


【解决方案1】:

在你调用的构造函数中

 while (true){

        objects.push_back(new c());
        // <------------

new c() 在没有任何输出之前再次调用构造函数。这再次调用构造函数,并再次将新的 c 推送到其objects,后者又再次调用构造函数。有一个永不停止的无限递归,程序流永远不会到达标有// &lt;------------的行。

【讨论】:

  • 哦,好吧,我应该删除新的,对吧?
  • 但是实验室要求我使用新的算子,那我该如何适应呢?
猜你喜欢
  • 1970-01-01
  • 2016-04-20
  • 2011-01-23
  • 2020-10-11
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
相关资源
最近更新 更多