Get the App
SLTechnology News&Howtos  ›  Development  › 

Optimization method of C++ operator overloading and return value

Shulou Source: shulou.com Published: 2022-05-31 19:52:43 09月21日 Update

This article introduces the knowledge of "C++ operator overloading and return value optimization". Many people will encounter this dilemma in the operation of actual cases. next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Problem background

   compilation environment is still for C6455 DSP, in order to do some simple image histogram processing, and as far as possible without the template class, I wrote a simple class to store the array with length information, and can do some simple operations. The subtraction operator is overloaded so that the difference between the two histograms can be found.

Specific problems

   remember to remind yourself to overload copy constructors and assignment operators when there are members of a class that need to allocate space dynamically. To give an example, I defined the following CData class.

Class CData {private: int * makeshift public: CData (); CData (unsigned int nLen); / * There is no copy constructor at the very begining * / CData (const CData & data); ~ CData (); int & at (unsigned int i); int & at (unsigned int i) const; CData operator- (const CData & data); CData & operator= (const CData & data); CData & operator-= (const CData & data);}

   has two members in CData, a pointer of type int and a variable of type unsigned int representing the number of data.

   I overloaded a subtraction operator to directly subtract the int type data at each corresponding location in two objects of type CData of the same length. When invoking subtraction, copy constructors and assignment operators are bound to be used, so they also need to be overloaded.

By the way,    mentioned that I also declared an overload of the "- =" operator above to highlight that "- =" would be more efficient in certain situations, but because I can't directly overwrite the data in "subtracted" in practical application, I can't use the "- =" operator, only through the subtraction operator.

CData CData::operator- (const CData & data) {cout

Tags: Objects operations functions copies operators subtraction data compilation time types members procedures problems two memory pointers methods clocking code content Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Tech Info Apple Shulou Information Redmi