将c ++引用的地址传递给指针

问题描述 投票:-2回答:1

我想将c ++引用传递给c风格的API,它只允许指针参数传递自定义数据。

在我的例子中,我只是将c ++引用的地址转换为指向void的指针(在一个名为“function”的函数中发生)。该指针被传递给c函数(称为“execute”),该函数也将回调函数作为参数。在回调函数实现(名为“callback”)中,我将指针void转换回指向std :: vector的指针。

这在MS Visual Studio 2017中编译时没有警告和错误,并按照需要运行(向量“v”包含从1到5的数字,并且它们也被打印)。但是,根据C ++标准,我担心这是有效的。

当然,使用全局std :: vector实例是可能的。但在某些情况下,如我的情况,这可能是一个糟糕的解决方案。因为在我的情况下,每次调用“function”时我需要一个std :: vector实例,因此不适合让一个全局实例替换参数。此外,全局实例在多线程环境中可能不合适,我希望在每个线程的调用堆栈上保留std :: vector的实例。用类包装std :: vector实例并将指针传递给std :: vector成员也不是我想要的。我对我使用的具体实现的技术观点颇为好奇。

简而言之,我们会认为这个例子是一个不好的做法吗?将Type的引用地址转换为void的指针并从指向void的指针强制转换为指向Type的指针是有效的,而忽略了指针者最初是对Type的引用。有替代品而不是我上面描述的那些吗?

请找到下面的最小工作示例:

#include <vector>
#include <iostream>

//
// The API of a 3rd party library (Typical C-Style Interface)
//

void execute(void (*callback)(void *, int[], int), void * context)
{
    int data [5] = {1,2,3,4,5};

    (*callback)(context, data, 5);
}

//
// My callback function fitting the signature for the 3rd party API
//

void callback(void * context, int data [], int size)
{
    std::vector<int> * v = (std::vector<int> *)context;

    for (int i = 0; i < size; i++) {
        v->push_back(data[i]);
    }
}

//
// Pass a reference to an std::vector as void * to the 3rd party API
//

void function(std::vector<int> & v)
{
    execute(callback, (void *)&v);
}

//
// Pass a std::vector as reference to a function
//
// Evaluate the result at the end
//

int main()
{
    std::vector<int> v;

    function(v);

    for (auto & e : v) {
        std::cout << e << std::endl;
    }

    return 0;
}
c++ c pointers reference
1个回答
0
投票

除了在定义上初始化之外,您无法对引用变量执行任何操作。初始化后每次使用引用变量都是对原始变量的直接访问,它引用的是什么。

在你的情况下,当你在函数&v中执行function时,你不会得到本地引用变量v的地址,而是来自v函数的变量main的地址。

简而言之,这很好。

© www.soinside.com 2019 - 2024. All rights reserved.