gpt4 book ai didi

c++ - 仿函数和 initializer_list 的拷贝

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:30:44 24 4
gpt4 key购买 nike

我对复制仿函数和/或初始化器时发生的情况感到有点困惑。在下面的代码中,我认为我会一直复制/移动对象,但不管它是否存在段错误。我似乎做错了什么,但还没有弄清楚,我的错误假设是什么。奇怪的是,在 cppreference.com 我找不到 initializer_list 的复制或移动构造函数,所以我想知道在这些情况下实际发生了什么。

#include <string>
#include <vector>
#include <functional>
#include <iostream>

std::initializer_list<std::function<std::string()>> getInitializer() {
return {
[]() -> std::string {
return "If";
}
};
}

int main() {
std::function<int(std::string)> func;
{
auto init = getInitializer();

func = [init](std::string text) -> int {
std::vector<std::function<std::string()>> vec(init);

for( auto& el : vec ) {
std::cout << el();
}
std::cout << text << std::endl;
return 5;
};
}

return func(" you see this - the world is all right!");
}

最佳答案

我对 initializer_list 没有太多经验s,但标准似乎建议实现 initializer_list就好像它是一对指向数组的指针。名单在getInitializer具有自动生命周期,支持它的数组也是如此。您最终会返回一对指向不再存在的数组的指针。

标准的相关部分是 8.5.4 [decl.init.list] 第 5 项和第 6 项:

5.- An object of type std::initializer_list<E> is constructed from an initializer list as if the implementation allocated an array of N elements of type E, where N is the number of elements in the initializer list. Each element of that array is copy-initialized with the corresponding element of the initializer list, and the std::initializer_list<E> object is constructed to refer to that array. If a narrowing conversion is required to initialize any of the elements, the program is ill-formed.

6.- The lifetime of the array is the same as that of the initializer_list object.


因此对于您的特定情况,实现大致等同于:

std::initializer_list<std::function<std::string()>> getInitializer() {
std::function<std::string()> __a[1] = {
[]() -> std::string {
return "If";
}
};
return std::initializer_list<std::function<std::string()>>(__a, __a+1);
}

关于c++ - 仿函数和 initializer_list 的拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11174293/

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