小编no.*_*nod的帖子

在 C++ 中使用函数装饰器(使用闭包)时出现意外的分段错误

我创建了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)

c++ lambda closures decorator

1
推荐指数
1
解决办法
52
查看次数

关于操作本机数组的快速问题

#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 ++之间的关系有一些误解.如果我错了,请纠正我.

c c++ arrays dynamic-memory-allocation

0
推荐指数
1
解决办法
53
查看次数