返回C++中向量元素的复制值

Returning copied value of vector element in C++

本文关键字:复制 元素 向量 C++ 返回      更新时间:2023-10-16

我已经在SO和谷歌上搜索了3个小时,但找不到我所看到的分辨率。

我有一个.cpp矢量支持程序,它为更大的c程序提供c++功能。我已经有了一个工作良好的queue.cpp,队列推送和弹出来回传递的值/元素的副本,因此函数的导出和构建正在进行。

当试图复制并返回向量中元素的值时,会出现问题。

在.c文件中的使用

        vector_type *temp;
        ...
        _Vector_At(VectorHandle, i, temp);
        if(temp == NULL)
            printf("nulln");
        printf("Returned %xn", temp);

.cpp:

typedef struct
{
    std::vector<vectory_type*> q;
    pthread_mutex_t mutex;
} VECTOR;
 ...
int _Vector_At(VECTOR_HANDLE handle, short index, vectory_type *ptr)
{
VECTOR *q = (VECTOR *)handle;
if (NULL == q)
{
  return(-1);
}
ptr = q->q[index];
printf("Test %xn", ptr);
return(0);
}

控制台输出为

Test <expected memory address>
null
Returned 0

我只能在访问器函数内部查询ptr指向的值。当ptr的值从.cpp程序返回到.c程序时,它会被擦除。但是,std::queue以完全相同的方式推送和弹出值,这并没有任何意义。

有人有什么想法吗?谢谢

在c代码中,将vector_type *temp传递给函数_Vector_At_Vector_At函数正在将指针的本地副本作为ptr,并使用它来修改值,但它并没有按照您的意愿返回该值。这是因为它是一个局部变量,它的生存期在_Vector_At函数结束时结束。要解决此问题,可以将指针作为引用或指针指针传递:_Vector_At(VECTOR_HANDLE handle, short index, vectory_type* &ptr)_Vector_At(VECTOR_HANDLE handle, short index, vectory_type** ptr)