Search code examples
c++eclipse-cdtgoogletest

Why does Eclipse-CDT say self-assignment is an error?


I was doing unit test in eclipse g++ using google test. I got an error when i tried to unit test the self assignment check in the class i designed.

as usual, the overload is pretty standard and looks like this:

CLASS operator=(const CLASS& rhs);

and when i tried to have this in the test:

CLASS A;
A = A;   //compile error here, saying self assignment to itself. have no clue why, though.

I wonder if there is a specific way for self assignment test. Thanks.

FYI, below is the snapshot of the error

enter image description here


Solution

  • A self assignment statement x = x; is not, of course, an error in C++ and you do not have any compiler error here.

    If you run a build of your project and look at the output in the IDE Console tab, rather than the Problems tab, you will see that the compiler does not report such an error. Unless it does report some error, you project will build successfully.

    If you look at the self-assignment error reported under the Problems tab you will see that its Type is Code Analysis Problem, not C/C++ Problem. This means that the problem is reported by the Eclipse CDT Code Analyser (Codan), not by the compiler.

    Codan is reporting self-assignment as an error because self-assignment is almost always a programming mistake. But in your case it is deliberate.

    You have two choices:

    • 1). Ignore the Code Analysis error
    • 2). Change the Code Analysis settings of the project so that this error is not reported.

    To do 2):

    • Navigate Properties -> C/C++ General -> Code Analysis
    • Enable Use project settings
    • Either:-
      • Disable problem Assignment to itself, or
      • Select Assignment to itself, then navigate Customize Selected... -> Preferences and change the problem's severity from Error to Warning or Info.
    • OK out of project Properties