Ctor Initializer: self initialization causes crash?

后端 未结 5 1093
我寻月下人不归
我寻月下人不归 2021-01-22 10:18

I had a hard time debugging a crash on production. Just wanted to confirm with folks here about the semantics. We have a class like ...

class Test {
public:
  Te         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-22 10:55

    The original "initialization" by assignment is completely superfluous.

    It didn't do any harm, other than wasting processor cycles, because at the time of the assignment the m_str member had already been initialized, by default.

    In the second code snippet the default initialization is overridden to use the as-yet-uninitialized member to initialize itself. That's Undefined Behavior. And it's completely unnecessary: just remove that (and don't re-introduce the original time-waster, just, remove).

    By turning up the warning level of your compiler you may be able to get warnings about this and similar trivially ungood code.

    Unfortunately the problem you're having is not this technical one, it's much more fundamental. It's like a worker in a car factory poses a question about the square wheels they're putting on the new car brand. Then the problem isn't that the square wheels don't work, it's that a whole lot of engineers and managers have been involved in the decision to use the fancy looking square wheels and none of them objected -- some of them undoubtedly didn't understand that square wheels don't work, but most of them, I suspect, were simply afraid to say what that they were 100% sure of. So it's most probably a management problem. I'm sorry, but I don't know a fix for that...

提交回复
热议问题