Search code examples
c++variableslinked-listoperator-precedence

Is it possible for me to check if the variable will be assigned with a value?


I have a matrix that is a nested linked list. I want to use operator overloading so that I can do matrix(x,y) to access a 'node'. The problem is, how do I check if that int& will be assigned with a value? The reason for this is because I do not want to create a 'node' unless it is being assigned with a value.

Structure:

Class Matrix -> when initialized (ex. matrix matrix(10,10), where 10x10 are the dimensions) the nested linked lists do not create the nodes in memory, they wait until the node is being modified, so if there is no 'node' then spacer value is 0.

int &operator() (row index, column index) -> when this is triggered (matrix(x,y)) then it basically searches for the linked list row (if not found it creates one with that index), it then searches the linked list column (if not found then it creates one with that index), after all this is done it return the data variable by reference.

So basically, I only want to do the top if I know the 'node' will be assigned with a value / initialized.

examples (NOTE: 'node' does not exist yet)

`` matrix(4,5) = 18; // return int& so that it can be assigned with 18 matrix(4,5); // do not create 'node' because it will not be assigned with a value


Note: this is just background info, please don't code everything and give me the answer. All I want to know is if there is a way that before `operator()` is called it checks for assignment so I know it will be assigned a value and won't just return for no reason.

Please don't tell me to do `operator(row indx, column indx, data)`, if possible I would like to keep the format of `matrix(row,column) = x`.

Solution

  • You can't.

    What you should do is mark operator() (or whatever you use to access element by index) as [[nodiscard]], so that anybody who tries to call it without using the value will get a compiler warning.

    This doesn't let you distinguish between reads and writes, so reading a non-existing element will create that element.

    If you don't want that, you need two separate functions for reading and writing elements, something like .set(x, y, value) and .get(x, y).


    Some might suggest to return a helper class from operator(), with an overloaded operator= (writing the element) and operator T (reading the element). But this is bad and evil, because operator T isn't always invoked automatically (e.g. when passing the object to a function template), and when it doesn't, your users will be confused.