1

I'd like to know if this code is valid or has an undefined behaviour, because my MSVC gives a warning C4355 this used in base member initializer list.

struct S
{
    string s_1;
    string s_2;

    S(string&& s_1, const string& s_2)
        : s_1{ std::move(s_1) },
        s_2{ s_2 + this->s_1 }
    {

    }
};

Is it allowed to use this pointer in this case? Compiled with MSVC with a flag /std:c++17.

Michal
  • 627
  • 3
  • 13
  • 1
    https://timsong-cpp.github.io/cppwp/n4659/class.base.init#15 [Note 7: The *expression-list* or *braced-init-list* of a *mem-initializer* is in the function parameter scope of the constructor and can use `this` to refer to the object being initialized. — end note] – Evg Aug 05 '21 at 07:49
  • 1
    That warning is to warn that not all members of `this` has been constructed / are available. (`s_1{this->s_2}` would be a mistake). It is fine usage here. – Jarod42 Aug 05 '21 at 07:54
  • 1
    delegating constructor might help to get rid of the warning: [Demo](https://godbolt.org/z/E1zK9asxG). – Jarod42 Aug 05 '21 at 08:02

0 Answers0