简体   繁体   English

如何使用数组成员将内存分配给类的实例?

[英]How is memory allocated to instances of class with array member?

In my understanding, under usual conditions, array is being allocated memory at compile time, but what happens when array is a member variable, and there is pretty much nothing to allocate memory to during compilation. 根据我的理解,在通常情况下,数组在编译时被分配内存,但是当数组是成员变量时会发生什么,并且在编译期间几乎没有什么可以分配内存。 Does it get implicitly dynamically-allocated, when instance of that class is created? 当创建该类的实例时,它是否隐式动态分配?

class Arr{
   public:
   int arr[10];
};

Arr doSomething(Arr &arg){
   return arg; //copy of arg created; 'copy=new int[10]' at this point?
}

int main(){
   Arr temp; 
   doSomething(temp);

   //if returned object's array was dynamically initialized
   //will it result the array in temp being released twice?
}

UPD. UPD。 In my case, situation rises when I try to subract AB where B>A. 在我的情况下,当我尝试减去B> A的AB时,情况会上升。 In these cases I can access array to read from it, but modifying its values leads to garbage. 在这些情况下,我可以访问数组来读取它,但修改它的值会导致垃圾。 Moreover, final output in main is fine. 而且, main最终输出很好。 Here's full code: 这是完整的代码:

#include <iostream>

using namespace std;

const int MAX_ARRAY_SIZE=256;

char* getOperatorIndex(char* equationString);
bool isOperator(char characterDec);
int* toIntArray(char* firstInA, char* lastInA, int* firstInB);

class Number{
    int* firstInNumber;
    int* lastInNumber;
    int number[MAX_ARRAY_SIZE];

    public:
    Number();
    ~Number();
    bool operator<(Number& b);
    int& operator[](int index);
    Number operator-(Number& b);
    void print();
    int length(){return lastInNumber-firstInNumber;}
    int*& lastPtr(){return lastInNumber;}
    int*& firstPtr(){return firstInNumber;}
};

Number::Number(){
    firstInNumber=number;
    lastInNumber=number;
}

Number::~Number(){
    cout<<"number destroyed"<<endl;
}

int& Number::operator[](int index){
    return number[index];
}

bool Number::operator<(Number& b){
    if(length()>b.length())return false;
    if(length()<b.length())return true;

    for(int a=0;a<length();++a){
        if(number[a]>b[a])return false;
        if(number[a]<b[a])return true;
    }
    return false;

}

void Number::print(){
    for(int a=0; a<=length(); ++a){
        cout<<number[a];
    }
    cout<<endl;
}

Number Number::operator-(Number& b){

    Number result;

    if(*this < b)
    {
        result=b-*this;
        cout<<*result.lastPtr()<<endl;
        result.print();
        *result.lastPtr()*=-1; // GARBAGE HERE
        cout<<*result.lastPtr()<<endl;
        return result;
    } 

    result[0]=0;

    for(int q=0; q<=length(); ++q)
    {

        if(b.length()-q >= 0)
        {
            result[q]+=(*this)[length()-q]-b[b.length()-q];

            if(result[q] < 0)
            {
                result[q]+=10;
                result[q+1]=-1;

            } 
            else
            {
                result[q+1]=0;
            }

        }
        else
        {
            result[q]+=(*this)[length()-q];

        }

    ++result.lastPtr(); 
    }

    do{
        --result.lastPtr();
    }while(!*result.lastPtr());

    return result;
}

int main(){
    char equationArray[MAX_ARRAY_SIZE*2+1];  // operandA(<=256) operator(1) operandB(<=256)
    Number a,b;

    cin>>equationArray;
    char* operatorPtr=getOperatorIndex(equationArray);

    a.lastPtr()=toIntArray(equationArray, operatorPtr, a.firstPtr());
    b.lastPtr()=toIntArray(operatorPtr+1, operatorPtr+strlen(operatorPtr), b.firstPtr());

    a.print();
    b.print();

    Number c;
    switch(*operatorPtr){
        case '-':
            c=a-b; 
            break;
    }
    c.print();

}


char* getOperatorIndex(char* equationString){
    while(!isOperator(*++equationString));   
    return equationString;
}

bool isOperator(char characterDec){
    if(characterDec>='*' & characterDec<='/')return true;
    return false;
}


int* toIntArray(char* firstInA, char* lastInA, int* firstInB){
    while(lastInA-firstInA>0){
        *firstInB=*firstInA-'0';
        ++firstInB;
        ++firstInA;
    }
    return --firstInB;  
}

All data members of a class have the same storage-duration as the class' object created. 类的所有数据成员与创建的类对象具有相同的存储持续时间 Hence in: 因此:

int main(){
   Arr temp; 
   doSomething(temp);
}

The data member temp.arr which is of type int[10]; 数据成员temp.arr ,类型为int[10]; also has automatic storage-duration .. (or what is inappropriately known as " stack object ") 还有自动存储持续时间 ..(或者不恰当地称为“ 堆栈对象 ”)


Arr doSomething(Arr &arg){
   return arg; //copy of arg created; 'copy=new int[10]' at this point?
}

No, there is no heap allocation here. 不,这里没有堆分配。 rather a member-wise copy by the implicit copy constructor. 而是由隐式复制构造函数构成的成员副本。 See How are C++ array members handled in copy control functions? 请参阅如何在复制控制功能中处理C ++数组成员?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否将分配类的数组成员的内存? - Will memory of array member of a class be allocated? 如何分配类中的静态成员? - How is a static member in a class allocated? 如何影响由 new 分配并强制转换为数组 od class 对象的 memory? - How to affect memory allocated by new and casted to an array od class objects? 如何在不删除 object 的情况下释放为 String class 成员分配的堆 memory - How to free the heap memory allocated for String class member without deleting the object 如何释放由链表实现的队列 class 的成员函数动态分配的 memory? - How to free the memory that is dynamically allocated by member functions of a Queue class which is implemented by Linked List? 什么时候为C ++中的类的成员函数分配了内存空间? - When is the memory space for a member function of a class in C++ allocated? 删除类成员动态分配的内存的最佳方法是什么 - What is the best way for deleting dynamic allocated memory of class member 为什么类成员函数破坏分配给指针参数的内存? - Why class member function destroies the memory allocated for a pointer argument? 为 struct 成员分配的内存是否连续? 如果结构成员是数组怎么办? - Is the memory allocated for struct members continguous? What if a struct member is an array? 如何使用抽象类将内存分配给实例数组? - How to allocate memory to an array of instances using an abstract class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM