Class method returning reference C++/SystemC

201 views Asked by At

To pass user-defined datatypes into SystemC channels templates requires these datatypes to be defined as a class that implements also different kind of operators <<, =, ==.

I need to define a sc_fifo such as:

sc_fifo<route_t>

For this to be correct, route_t datatype has to be written as in the below example.

class route_t
{
    public: 
    route_dir_t                     route_dir; 
    unsigned int                    vc_index; 

    // methods allowing the structure to be passed into SystemC channels
    // constructor
    route_t(route_dir_t _route_dir, unsigned int _vc_index) {
        route_dir = _route_dir; 
        vc_index  = _vc_index; 
    }

    inline bool operator == (const route_t& _route) const {
        return (route_dir == _route.route_dir && vc_index == _route.vc_index); 
    }

    inline route_t& operator = (const route_t& _route) {
        route_dir = _route.route_dir; 
        vc_index  = _route.vc_index; 
        return *this; 
    }

}; // end class route_t 
  1. Why does SystemC require such an implementation?
  2. Why does the operator= need to return a reference to the object itself? It just updates the internal members.
  3. Can the datatype be defined as a struct instead with internal methods implementing the required operators?
  4. Why is inline used in this context?
  5. How can returning *this be equivalent to returning a reference to the object as expected in the declaration of the method?
2

There are 2 answers

0
Motti On

operator= is expected to return a reference to the class itself so you can do any of the following.

a = b = c;
if (a = b) { } // check the resulting value of a
(a = b).foo();

Although these may not be things you expect to do it follows the general guideline of having user defined objects behave in the same way as built in objects behave.

As for returning a reference, you have to make sure that you don't return a reference to a local object but it has the expected semantics.

0
Glenn Teitelbaum On

Look at the following:

Myclass a, b, c;

a=b=c=otherMyclass;

For that to work, each operator= must return the reference to be used by the next in the chain.

Also you should generally check that the assignment is not to itself

    inline route_t& operator = (const route_t& _route) {
   if (&_route != this)
   {
        route_dir = _route.route_dir; 
        vc_index  = _route.vc_index; 
        return *this; 
    }
}

This will handle:

   a=a;