Search code examples
c++delegating-constructor

Why partially initializing a class and then invoking delegating ctor fails?


Following code does not initialize struct string members to same value.

#include <string>
#include <iostream>

struct S
{
    std::string s1;
    std::string s2;
    S(std::string const& s) : s1{s}{}
    S(int i) : S([&]{
        s2 = std::to_string(i);
        return std::to_string(i);
    }())
    {}
};

int main()
{
    S s{123};
    std::cout << s.s1 << "|" << s.s2;

    return 0;
}

I'm getting segmentation fault in gcc (tried different versions), and 123| in clang (different versions also) through Wandbox.

I'm getting a read access violation Visual Studio 15.9.16

Thank you.


Solution

  • The argument you give to the constructor (i.e. the lambda) cannot access internal members, because they have not been constructed yet.

    This should work:

    struct S
    {
        std::string s1;
        std::string s2;
        S(std::string const& s) : s1{s}{}
        S(int i)
          : S(std::to_string(i))
        {
            s2 = s1;
        }
    };