如何从函数中正确返回向量

How to correct return vector from function?

本文关键字:返回 向量 函数      更新时间:2023-10-16

你能帮我解决这个问题吗?我想要返回向量从函数在类类型到主函数:

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()中分配的内存永远不会被释放。