开发者

C++: Initialization Lists / Naming conventions

The following code works on my machine, but is it good practice / guaranteed to work?

struct MyStruct {
   MyStruct(int x, int y, int z) :
       x(x),
       y(y),
       z(z) {
   }

   int x;
   int y;
   int z;
};

Specifically, is x(x) guaranteed to do what I want? (that is, does the variable in an initialization list always look at that struct/class' member?)

I don't want to开发者_开发百科 use leading or trailing underscores since x is a public member of the struct.

Thanks!


Yes, that is guaranteed to do what you expect.

The only thing that can exist "outside" the parentheses in an initializer list are member variables. And inside the parentheses, the usual rules apply; local variables hide member variables.

As to whether it's good practice, well, consider what happens if you accidentally remove one or more of the arguments from the constructor argument list. The code will still compile fine! But it will break horribly at runtime. Nevertheless, I still use this pattern fairly frequently.


While it expects what you do, imagine this situation by extension:

class MyStruct {
public:
   MyStruct(int x, int y, int z)
   :   x(x),
       y(y),
       z(z) 
   {   }
   int x() const;
   int y() const;
   int z() const;

private:
   int x;
   int y;
   int z;
};

Which will not work. That's why I prefix my class members with m_. This allows very readable code with a hint to the reader that the identifier in question is part of the class. Non-prefixed identifiers are either function arguments (like in the constructor initializer list: m_x(x), or function local variables).


Yes, x(x) does exactly what you want. x(x) is a name of the member, and x(x) is a formal argument.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜