创建 std::function 克隆时的未定义行为

问题描述 投票:0回答:1

我尝试实现

std::function
的克隆。为了简单起见,我想创建一个像
std::function
这样的类来处理类型
int(*)(int)

我面临复制构造函数的问题。当调用对象(使用复制构造函数创建)的调用运算符时,sanitizer 会检测到未定义的行为。由于未释放分配的内存,代码存在潜在的内存泄漏。 调用 a3(5) 时程序崩溃

#include <iostream>
#include <functional>

int foo(int x )
{
    return x;
}

int bar(int x )
{
    return x*x;
}

class A
{
public:
    A(int(*f)(int))
     :callable_{+[](void *data, int x)->int{
                auto & obj = *static_cast<typename std::decay<int(*)(int)>::type *>(data);
                return obj(x);
    }}
    {    
        f_ = new std::decay<int(*)(int)>::type(f);
    }

    A(A const & other)
    {
        callable_ = other.callable_;
        f_ = new std::decay<int(*)(int)>::type(std::decay<int(*)(int)>::type(other.f_));
    }

    A & operator = (A const & other)
    {
        callable_ = other.callable_;
        f_ = new std::decay<int(*)(int)>::type(std::decay<int(*)(int)>::type(other.f_));
        std::cout << f_ << std::endl;
        return *this;
    }

    int operator()(int x)
    {
        return callable_(f_,5);
    }

    void * f_;
    int (*callable_)(void *data,int) = {};
};

int main() {
    A a1(foo);
    A a2(bar);
    A a3(a1);
    std::cout << a3(5) << std::endl;
}

有什么想法吗?

演示

c++ undefined-behavior
1个回答
0
投票

不是为函数对象f分配内存,而是为指向this的指针分配内存。 为了正常工作,分配更改为

 A(const A &other)
    {
        callable_ = other.callable_;
        f_ = new FunctionFunc(*other.f_);
    }
© www.soinside.com 2019 - 2024. All rights reserved.