Ctor Initializer: self initialization causes crash?

后端 未结 5 1152
我寻月下人不归
我寻月下人不归 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 11:03

    The first constructor is equivalent to

      Test()
      : m_str()
      {
        // members initialized ...
        m_str = m_str;
      }
    

    that is, by the time you get to the assignment within the constructor, m_str has already been implicitly initialized to an empty string. So the assignment to self, although completely meaningless and superfluous, causes no problems (since std::string::operator=(), as any well written assignment operator should, checks for self assignment and does nothing in this case).

    However, in the second constructor, you are trying to initialize m_str with itself in the initializer list - at which point it is not yet initialized. So the result is undefined behaviour.

    Update: For primitive types, this is still undefined behaviour (resulting in a field with garbage value), but it does not crash (usually - see the comments below for exceptions) because primitive types by definition have no constructors, destructors and contain no pointers to other objects.

    Same is true for any type that does not contain pointer members with ownership semantics. std::string is hereby demonstrated to be not one of these :-)

提交回复
热议问题