我创建了decorator函数来向现有函数添加功能。该程序输出正确的函数指针地址以及helloworld按预期迭代 10 x所用的时间。
然而,如果我将decorator函数更改为采用original_functionby 值 ( FunctionPointer original_function),程序将因分段错误而终止,我不明白它失败的原因。
#include <iostream>
#include <chrono>
typedef void (*FunctionPointer)();
auto
decorator(FunctionPointer && original_function) // if changed to FunctionPointer original_function, it causes segmentation fault when the closure(lambda expression) is called later on
{
std::cout << "Decorator: " << (void*)original_function << std::endl; // 0x558072fb0b90
return [&]()
{
std::cout << "Decorator: " << (void*)original_function << std::endl; // 0x558072fb0b90 but 0x0 when original_function passed by value
auto t0 = …Run Code Online (Sandbox Code Playgroud) #include <iostream>
int
main(void)
{
int n;
std::cin >> n;
int x[n];
return 0;
}
Run Code Online (Sandbox Code Playgroud)
从C的角度来看,上面的代码不应该正确编译,因为我猜想数组'x'的大小还没有定义.
只有在用户传递变量'n'的参数后,才能定义'x'的大小,但编译和运行时代码没有崩溃,我想知道为什么.
如果它是用C语言编写的,我认为人们会将malloc用于运行时可配置数组.
也许我对数组,内存分配,编译器以及c和c ++之间的关系有一些误解.如果我错了,请纠正我.