Search code examples
c++randomcopy-constructordynamic-memory-allocationassignment-operator

C++ | Are random constrained arrays considered resources?


I am taking a class on C++. In our text is says:

Memory that an object allocates at run-time represents a resource of that object's class.

If an array has a random length, is it considered a resource and thus require a copy constructor/assignment operator?

class someclass{


    public :
        int length;
        int* randomarray;

};

int main(){

    someclass obj;

    obj.length = rand() % 50 + 1;

    obj.randomarray = new int[obj.length];

    return 0;

}

Edit>> This is a terminology question.


Solution

  • In C++ the word 'resource' has a specific meaning, in relation to the idiom "resource acquisition is initialization", which I assume is what you are learning about and what the question is really asking.

    In simple terms, a resource is something that, after you acquire it, you have to clean it up / release it. Meaning, put it back where you found it, return it to the system, etc., and typically because, someone else (some other program) might want to use it soon. It could be a piece of hardware, like a device, maybe a printer. It could be, a software construct, like a lock used in threading. Or it could be simply memory.

    When you get random bits from a function like rand, you don't need to give them back to anyone or anything, and no one else is going to use them after you are done with them. You can just forget about them afterwards. So they should not be considered a resource for purposes of this idiom, or the rule of three, etc. If the random bits are passed around via heap-allocated memory, then that is a resource that might need to be freed. But I would say in that case that the random bits are not the resource, only the memory that contains them is.