简体   繁体   中英

C++ struct constructor with member initializer list

I came across a C++ struct definition with a constructor.

struct Foo                                                                                                                                                                                                                                   
{
    int x;

    Foo( int _x ) : x(_x)
    {   

    }   
    ~Foo()
    {   
        std::cout << "Destructing a Foo with x=" << x << "\n";
    }   
};

I know about member initializer but don't quite get what _x means here? Can someone please enlighten me?

It means a variable named "_x". The underscore can be used in names of variables like letters, although identifiers whose names start with underscores have a long standing convention as being reserved for the compiler's library.

int _x;

Means the same thing that

int x;

means. Or "int a;", "int b;", or int anything. Variable names in C and C++ may start with underscores or letters, and consist of underscores, letters, and digits. Although, as I said, leading underscores should be avoided, as they're generally reserved for use by the compiler's library.

That's not kind of special or magic syntax. The prefixed _ is used to distinguish the constructor parameter from the member variable symbol. That's all.

Using a definition like

struct Foo {
    int x;
    Foo( int x ) : x(x) {}
};

would just be ambiguous scope wise.

Foo( int _x ) : x(_x)
{   

}

This is a constructor that takes an integer which is then used to initialize the value of member variable x .

Foo f(5);
// -> f.x = 5

The reason for the underscore is to disambiguate between the function parameter and the variable it's being assigned to.

YMMV: Many development teams use similar strategies:

. Prefix all member variables with "m_", . Prefix or suffix member variables with "_", eg _x , x_ ,

It's not very common but you'll find some development teams who always disambiguate function parameters with a prefix:

class Foo {
    int m_x; // member x
public:
    Foo(int _x) : m_x(_x) {}
    int x() const { return m_x; }
};

the advantage of this approach: you can have lowercase member function names which won't conflict with parameters, so you can have getters that aren't prefixed with 'get'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM