c++ declaring objects with curly braces

五迷三道 提交于 2019-12-07 08:12:44

问题


When declaring objects in c++ -

What is the difference between

MyClass myObj (a,b,c);

(I understand this as invoking the constructor that takes three arguments)

vs.

MyClass myObbj{a,b,c};

Not sure what the curly brackets here mean?

As a reference I am using the following code

// Inertial Navigation EKF
NavEKF EKF{&ahrs, barometer, sonar};
AP_AHRS_NavEKF ahrs{ins, barometer, gps, sonar, EKF};

1. Is the use of curly brace as in NavEKF EKF{&ahrs, barometer, sonar}; part of c++ standard. gcc 4.6.1 complains that - Function definition does not declare parameters.

2. Given AP_AHRS_NavEKF ahrs;

AP_Baro barometer;

RangeFinder sonar;

2A. Why would the compiler complain about this

NavEKF EKF(&ahrs, barometer, sonar);

but allow this

NavEKF EKF(AP_AHRS_NavEKF &ahrs, AP_Baro barometer, RangeFinder sonar);


回答1:


The basic intent is that they usually mean the same thing. The big difference is that curly braces eliminate the "most vexing parse" where you tried to define an object, but end up actually declaring a function instead.

So, NavEKF EKF{&ahrs, barometer, sonar}; is usually going to be equivalent to NavEKF EKF(&ahrs, barometer, sonar);. However, if you had something like: NavEKF EKF(); vs. NavEKF EKF{}; they're different--NavEKF EKF(); declares a function named EKF that takes no parameters and returns a NavEKF, whereas NavEKF EKF{}; does what you'd (probably) usually expect, and creates a default-initialized object named EKF of type NavEKF.

There are cases, however, where there's ambiguity about how to interpret things, and the ambiguity is resolved differently depending on whether you use parentheses or braces. In particular, if you use curly braces, and there's any way to interpret the contents as an initializer_list, that's how it'll be interpreted. If and only if that fails, so it can't be treated as an initializer_list, it'll look for an overload that takes the elements in the braces as parameters (and at this point, you get normal overload resolution, so it's based on the best fit, not just "can it possibly be interpreted to fit at all?")




回答2:


The curly braces is what is called 'uniform initialization'. The term is not part of C++ standard, but it is widely understood and is easily researchable. In particular, in the context provided, it means 'call constructor of MyObj with given arguments'.




回答3:


Using parenthesis invokes a constructor, which then chooses how to initialize the data members as needed.

Using curly braces initializes the data members directly - unless there is a constructor defined that takes a std::initializer_list as input, in which case the braces form the list of values that gets passed to that constructor.



来源:https://stackoverflow.com/questions/34007862/c-declaring-objects-with-curly-braces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!