Skip to main content

C++: Operator= returns const reference of *this or reference of *this?

Abstract

Recently, I started to use cppcheck. cppcheck suggested me that the return type of operator= should reference of (*this). But I thought this should be const reference of (*this). I thought the reason of this.

Contents

Cppcheck is an static analysis tool for C/C++ code. (http://cppcheck.sourceforge.net/) I found this tool is quite useful since it sometimes finds a memory leak error and so on. However, the following code has some style error at the operator=.

#include 
class OpTest {
public:
    /// constructor
    OpTest(int init_int) : m_int(init_int){
        // empty
    }
    /// operator= with const reference
    OpTest const & operator=(OpTest const & rhs){
        if(this != &rhs){
            m_int = rhs.m_int;
        }
        return *this;
    }
public:
    int m_int;
};

cppcheck said:
[operator_substitute_00.cpp:9]: (style) 'OpTest::operator=' should return 'OpTest &'.
I thought when I finished substitution of an instance, I consider the instance (= *this) should be const. Therefore, I was puzzled when I saw this message. I look up web, but I could not find a page that explains why this should be. Although, many of code returns just a reference of (*this).

I asked several colleagues about this. Then Ali answered me that: maybe you can call the non const method after the substitution. The following code is an example.
OpTest a(0);
OpTest b(1);
(a = b).non_const_method();
I see a point, but personally, I would prefer the following code.
OpTest a(0);
OpTest b(1);
a = b;
a.non_const_method();

Comments

Hi!

I am a cppcheck developer and I saw this post.

Yes there are good safety reasons to use const. But I still recommend that you don't use const.

The reason you should return a non-const reference is for consistency. That is how the old C types such as int, char, short, etc work. That is how the C++ types such as std::string, std::vector, etc work.

This is valid C code:
int a = 1, b = 2;
int &c = (a = b);
c = 3; // modify a

Similar code can be written using std::string, std::vector, etc.

Regards, Daniel
Shitohichi said…
Thanks for the comment. I see now why cppcheck suggests this.

Also thanks for the cppcheck, that's a great free software.

Popular posts from this blog

Why A^{T}A is invertible? (2) Linear Algebra

Why A^{T}A has the inverse Let me explain why A^{T}A has the inverse, if the columns of A are independent. First, if a matrix is n by n, and all the columns are independent, then this is a square full rank matrix. Therefore, there is the inverse. So, the problem is when A is a m by n, rectangle matrix.  Strang's explanation is based on null space. Null space and column space are the fundamental of the linear algebra. This explanation is simple and clear. However, when I was a University student, I did not recall the explanation of the null space in my linear algebra class. Maybe I was careless. I regret that... Explanation based on null space This explanation is based on Strang's book. Column space and null space are the main characters. Let's start with this explanation. Assume  x  where x is in the null space of A .  The matrices ( A^{T} A ) and A share the null space as the following: This means, if x is in the null space of A , x is also in the null spa

Gauss's quote for positive, negative, and imaginary number

Recently I watched the following great videos about imaginary numbers by Welch Labs. https://youtu.be/T647CGsuOVU?list=PLiaHhY2iBX9g6KIvZ_703G3KJXapKkNaF I like this article about naming of math by Kalid Azad. https://betterexplained.com/articles/learning-tip-idea-name/ Both articles mentioned about Gauss, who suggested to use other names of positive, negative, and imaginary numbers. Gauss wrote these names are wrong and that is one of the reason people didn't get why negative times negative is positive, or, pure positive imaginary times pure positive imaginary is negative real number. I made a few videos about explaining why -1 * -1 = +1, too. Explanation: why -1 * -1 = +1 by pattern https://youtu.be/uD7JRdAzKP8 Explanation: why -1 * -1 = +1 by climbing a mountain https://youtu.be/uD7JRdAzKP8 But actually Gauss's insight is much powerful. The original is in the Gauß, Werke, Bd. 2, S. 178 . Hätte man +1, -1, √-1) nicht positiv, negative, imaginäre (oder gar um

Why parallelogram area is |ad-bc|?

Here is my question. The area of parallelogram is the difference of these two rectangles (red rectangle - blue rectangle). This is not intuitive for me. If you also think it is not so intuitive, you might interested in my slides. I try to explain this for hight school students. Slides:  A bit intuitive (for me) explanation of area of parallelogram  (to my site, external link) .