Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why locally defined struct in function need assignment operator & copy constructor

Tags:

c++

struct

Can someone help me understanding this error , when i declare struct locally in function i get below errors from compiler. But error vanishes when i declare struct outside of function.

Note : I did not implement missing function intentionally. I just wanted to know why compiler need them when i am not using in my code.

RAII::RAII' : local class member function does not have a body

RAII::operator =' : local class member function does not have a body

void someclass::somefun()
{
    static bool inProgress = false; 
    struct RAII
    { 
        RAII(bool& f):flag(f){ flag = true;}
        ~RAII() { flag = false; }
        bool& flag;
    private:
        RAII(const RAII& rhs);
        RAII& operator= (const RAII& rhs);
    };
    RAII autoreset(inProgress);

    // Do something 

}
like image 878
Satbir Avatar asked Nov 30 '25 09:11

Satbir


1 Answers

So the standard contains this rule: 9.3.1p8

Member functions of a local class shall be defined inline in their class definition, if they are defined at all.

This outlaws out-of-line definitions of members of local classes.

The Microsoft compiler is apparently paranoid about this and has a level 1 warning C4822, where it warns the moment you declare a member without defining it. This is completely braindead - it should just give a good error message when you actually do define a member out of line.

The correct thing to do is to disable this warning in every project ever and keep doing what you were doing.

Edit: Apparently, the people at Microsoft also realized just how stupid this warning was and removed it in newer versions. MSDN does not contain documentation for this warning for versions newer than Visual Studio 2008.

like image 165
Sebastian Redl Avatar answered Dec 02 '25 23:12

Sebastian Redl