Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

Four Habit-Forming Tips to Faster C++

MyData myFunction() {
    return MyData(); // Create and return unnamed obj
}

MyData abc = myFunction();
MyData myFunction() {
    MyData result;           // Declare return val in ONE place

    if (doing_something) {
        return result;       // Return same val everywhere
    }
    // Doing something else
    return result;           // Return same val everywhere
}

MyData abc = myFunction();
MyData myFunction() {
    if (doing_something)
        return MyData();     // RVO expected

    MyData result;

    // ...
    return result;           // NRVO expected
}

MyData abc = myFunction();
void convertToFraction(double val, int &numerator, int &denominator) {
    numerator = /*calculation */ ;
    denominator = /*calculation */ ;
}

int numerator, denominator;
convertToFraction(val, numerator, denominator); // or was it "denominator, nominator"?
use(numerator);
use(denominator);
struct fractional_parts {
    int numerator;
    int denominator;
};

fractional_parts convertToFraction(double val) {
    int numerator = /*calculation */ ;
    int denominator = /*calculation */ ;
    return {numerator, denominator}; // C++11 braced initialisation -> RVO
}

auto parts = convertToFraction(val);
use(parts.numerator);
use(parts.denominator);
template <class T>
complex<T> &complex<T>::operator*=(const complex<T> &a) {
   T r = real * a.real – imag * a.imag;
   imag = real * a.imag + imag * a.real;
   real = r;
   return *this;
}
template <class T>
complex<T> &complex<T>::operator*=(const complex<T> &a) {
   T a_real = a.real, a_imag = a.imag;
   T t_real =   real, t_imag =   imag; // t == this
   real = t_real * a_real – t_imag * a_imag;
   imag = t_real * a_imag + t_imag * a_real;
   return *this;
}

18 Comments

21 - Jul - 2016

Eric Lemanissier

21 - Jul - 2016

Marc Mutz

10 - Nov - 2016

Olumide

21 - Jul - 2016

Eric Lemanissier

22 - Jul - 2016

Marc Mutz

25 - Jul - 2016

Oriol

25 - Jul - 2016

Marc Mutz

26 - Jul - 2016

Ivan Čukić

string getline()
void getline(string &)

26 - Jul - 2016

Marc Mutz

string getline(string = string());

25 - Aug - 2016

Ion

22 - Aug - 2016

Mudassir

22 - Aug - 2016

Marc Mutz

27 - Aug - 2016

Yehezkel

7 - Feb - 2017

Edward Welbourne

30 - May - 2021

Andy Gryc

29 - May - 2021

Adam

30 - May - 2021

Andy Gryc

31 - May - 2021

Marc Mutz

01_NoPhoto

Andy Gryc

Co-Founder at Third Law autotech marketing

01_NoPhoto

Marc Mutz

Former KDAB employee

Learn Modern C++

Learn more