gpt4 book ai didi

c++ - 为什么部分初始化一个类然后调用委托(delegate) ctor 失败?

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:34 28 4
gpt4 key购买 nike

以下代码不会将结构字符串成员初始化为相同的值。

#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;
}

我在 gcc 中遇到段错误(尝试了不同的版本),和 123| 通过 Wandbox 在 clang 中(也有不同的版本)。

我遇到读取访问冲突 Visual Studio 15.9.16

谢谢。

最佳答案

您提供给构造函数的参数(即 lambda)无法访问内部成员,因为它们尚未构造。

这应该有效:

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;
}
};

关于c++ - 为什么部分初始化一个类然后调用委托(delegate) ctor 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58025202/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com