如何从函数中正确返回向量
How to correct return vector from function?
你能帮我解决这个问题吗?我想要返回向量从函数在类类型到主函数:
class type:
vector<Test*> NetworkType::createObject(int r1, int r2, r3) {
vector<test*> te0;
if (res1 == 1 && res2 == 1 && res3 == 1) {
TestV *p1 = new TestV("aaa","bbb",3,"ooo","ccc", "ttt", "testX", "sk2");
TestV *p3 = new TestV("rrr","ddd",3,"ooo","ccc", "ttt", "testY", "sk2");
//return p1;
TestV tesV1(*p1);
te0.push_back(&tesV1);
TestV tesV2(*p3);
te0.push_back(&tesV2);
return te0;
} else {
...
}
}
主:Typ nk;
vector<Test*> p;
p = nk.createObject(p0,p1,p2);
输出:for(int i = 0; i < p.size(); i++){
cout << "n" + toString(p[i]);
}
toString:
std::string toString(Test* arg) {
TestV* teV = dynamic_cast<TestV*>(arg);
TestN* teN = dynamic_cast<TestN*>(arg);
if (teV)
{
return teV->toString();
}
else
{
return teN->toString();
}
return "";
};
编译是正确的,但是在运行程序之后,我得到了这个错误:
在volbahoney .exe: microsoftc++中0x76dac41f的未处理异常异常:std::__non_rtti_object在内存位置0x002fec9c..
感谢您的回复
这与向量和函数的返回值无关。异常消息清楚地说明了什么是错误的:您假定的对象实际上不是对象-因为您将具有自动存储持续时间的块范围对象的地址("局部变量")放入向量,这是无效的,因此您的程序调用未定义行为。
(这只适用于
te0.push_back(&tesV1);
不是te0.push_back(&hpv1);
(您的代码中有几个拼写错误,我假设您的意思是"tesV1"而不是"hpv1",并且始终是"Test"或"Test"等等)
在createObject()函数中将指针推入堆栈中分配的变量:
TestV tesV1(*p1);
te0.push_back(&hpV1);
HoneypotV tesV2(*p3);
te0.push_back(&hpV2);
这些对象是在堆上分配的对象的副本(带有"new"),但这无关紧要。一旦作用域结束(当您从函数返回时),堆栈上的对象就会消失。在此之后对指针解引用,就会遇到麻烦。
你想做什么并不完全清楚,但是如果你直接把指针推到堆分配的对象上,你就不会遇到这种麻烦:
te0.push_back( p1 );
te0.push_back( p2 );
还请注意,当您使用"new"分配对象时,通常期望您也使用"delete"取消分配它。您所编写的代码会泄漏内存——在createObject()中分配的内存永远不会被释放。
相关文章:
- 如何返回向量的常量引用?
- 如何在C++中返回向量的从零开始的索引
- 当函数返回C++向量实例时,它正在运行
- 从函数返回向量以打印内容
- 返回向量的单个索引值
- 为什么我不能返回向量<向量<int>>(进程返回 -1073741819 (0xC0000005))
- 返回向量元素的 l 值的正确方法是什么?
- 为什么通过引用返回向量比通过移动返回要快得多?
- 返回向量 C++ 上的递归
- C++ std::find() 寻址返回向量的类函数时的意外行为
- 如何在返回向量中访问系数
- C++ 函数返回向量中最小的正整数
- 查找并将指针返回向量中的对象
- getCompatibleComponent返回向量错误
- 如何从 JNI 返回向量<向量<float>>?
- 为什么下面的代码返回向量大小为 10
- 从函数返回向量时C++中止(核心转储)
- 如何正确地将向量<int>转换为空隙*并返回向量<int>?
- 接口 PTR 的返回向量C++
- C++ cv::Mat 返回向量的<rectangle>线程异步