草庐IT

c++ - 为什么我无法在 for 循环中访问动态分配的内存?

coder 2024-02-02 原文

我为从基类 instrument 继承的子类类型 stock 新建了一个内存,当我尝试访问我的数组的第二个元素时,它抛出错误。当我的新数组大小为 1 时一切正常

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class Instrument{

public:
    virtual void display(){}
    virtual void output(){}
    virtual void readFile(){}
    virtual ~Instrument(){}
};
class Stock : 
    public Instrument{
public:
    Stock(){

    }
    virtual void input(){
        cout << "This is stock, please input its information: ";
        cin >> name >> bidPrice >> askPrice >> lastPrice >> issueExchange;
    }
    virtual void display(){
        cout <<"This is to display stock: "<< name << " "
            << bidPrice << " "
            << askPrice << " "
            << lastPrice << " "
            << issueExchange << " "
            << endl;
    }
    virtual void output(){
        ofstream myfile;
        myfile.open("Stock.txt", ios::out | ios::app);
        if (myfile.is_open()){
            myfile << "This is a stock: "
                << name << " "
                << bidPrice << " "
                << askPrice << " "
                << lastPrice << " "
                << issueExchange << " "
                << endl;
        }
        else cout << "Unable to open file";
    }
    virtual void readFile(){
        string line;
        ifstream myfile("Stock.txt");
        cout << "\nThis is file stored\n";
        if (myfile.is_open())
        {
            while (getline(myfile, line))
            {
                cout << line << '\n';
            }
            myfile.close();
        }
    }
    virtual ~Stock(){}
private:
    char name[13];
    double bidPrice;
    double askPrice;
    double lastPrice;
    int issueExchange;

};


int main(){

    const int N = 5;//it works fine if I use N=1;
    Instrument *pBase = NULL;
    pBase = new Stock[N];

    for (int i = 0; i < N; i++){
        pBase[i].input();// here throws an exception and ends the program
        pBase[i].display();
        pBase[i].output();
    }
    pBase[N - 1].readFile();
    delete[] pBase;

    system("pause");
    return 0;

} 

最佳答案

多态性和指针算法不能混合,因为对象在数组中的排列取决于最派生的大小,而多态性会丢失该信息。动态分配是一个转移注意力的问题,你可以看到同样的问题:

Derived array[2];
Base* p = array;

printf("%p\n", &array[0]);
printf("%p\n", p);
printf("%p\n", &array[1]);
printf("%p\n", p + 1);

printf("%z\n", sizeof (array[0]));
printf("%z\n", sizeof (*p));

注意指针值使用array通过 sizeof (Derived) 向前推进, 但指针算法使用 p正在通过 sizeof (Base) 前进而没有找到真实的对象。

通常您会使用 Base* 的数组来解决这个问题, 而不是单个 Base*结合指针运算。

Base* pp[2];
for( auto& elem : array ) pp[&elem - array] = &elem;

printf("%p\n", &array[1]);
printf("%p\n", pp[1]);

// use (*pp[1]) or pp[1]->whatever

另一种选择是使用一个能记住原始类型的对象:

Derived* allocated = new Derived[N];
std::function<Base& (int)> poly = [allocated](int i){ return allocated[i]; };

并使用poly(i)而不是 p[i]

但是警告,你不能做 delete [] &poly(0);因为delete[]也不是多态的。

使用 std::unique_ptr<Derived[]>std::bind ,当访问器对象最终超出范围时,可以安排自动释放。

关于c++ - 为什么我无法在 for 循环中访问动态分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28753007/

有关c++ - 为什么我无法在 for 循环中访问动态分配的内存?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  3. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  4. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  7. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  8. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  9. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  10. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

随机推荐