【发布时间】:2018-11-28 12:48:10
【问题描述】:
伙计们,我有这样的功能(这是给定的,不应修改)。
void readData(int &ID, void*&data, bool &mybool) {
if(mybool)
{
std::string a = "bla";
std::string* ptrToString = &a;
data = ptrToString;
}
else
{
int b = 9;
int* ptrToint = &b;
data = ptrToint;
}
}
所以我想在循环中使用这个函数并将返回的函数参数保存在一个向量中(对于每次迭代)。 为此,我编写了以下结构:
template<typename T>
struct dataStruct {
int id;
T** data; //I first has void** data, but would not be better to
// have the type? instead of converting myData back
// to void* ?
bool mybool;
};
我的 main.cpp 然后看起来像这样:
int main()
{
void* myData = nullptr;
std::vector<dataStruct> vec; // this line also doesn't compile. it need the typename
bool bb = false;
for(int id = 1 ; id < 5; id++) {
if (id%2) { bb = true; }
readData(id, myData, bb); //after this line myData point to a string
vec.push_back(id, &myData<?>); //how can I set the template param to be the type myData point to?
}
}
或者没有模板有更好的方法吗?我用的是c++11(我不能用c++14)
【问题讨论】:
-
Guys I have a function like this (this is given and should not be modified).谁给的?该函数中有很多未定义的行为。 -
谁给你这个功能需要停止编码。您正在获取指向局部变量的指针,这意味着当函数结束时它们是悬空指针。
-
返回一个局部变量的地址。把它还给给你的人。
-
你能引用
void指针吗? -
@codekaizer:可以吗?是的。应该?没有。
标签: c++ pointers pass-by-reference