Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

c++ - missing string after returning object

I am trying to return an array of objects containing an integer and string, but after the return the string in the object is empty. Can someone help me please? I am a newbie.

CTransponder *CVerwaltung::Initial(){
CTransponder Transpo[10] =
{
    CTransponder("Chef", 100),
    CTransponder("Chefin", 101),
    CTransponder("Sekretaerin", 102),
    CTransponder("Werksleiter", 200),
    CTransponder("Produktionsleiter", 201),
    CTransponder("Angestellter", 300),
    CTransponder("Angestellter2", 301),
    CTransponder("Hausmeister", 400),
    CTransponder("Putzkraft", 401),
    CTransponder("Aushilfe", 500)
};
return Transpo;

Before the return, everything is as it should be, but after the string is empty.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are returning a pointer to a local array that goes out of scope and gets destroyed when the function exits, thus destroying the objects in the array. The caller ends up receiving a dangling pointer to invalid memory, and accessing the elements via that pointer is undefined behavior.

Consider returning a std::vector<CTransponder> or std::array<CTransponder, 10> instead, eg:

std::vector<CTransponder> CVerwaltung::Initial(){
    return std:vector<CTransponder>{
        CTransponder("Chef", 100),
        CTransponder("Chefin", 101),
        ...
    };
}

Otherwise, make the array be a member of CVerwaltung, eg:

class CVerwaltung{
private:
    CTransponder Transpo[10];
public:
    CVerwaltung();
    CTransponder* Initial();
};

CVerwaltung::CVerwaltung() {
    Transpo[0] = CTransponder("Chef", 100);
    Transpo[1] = CTransponder("Chefin", 101);
    ...
}

CTransponder* CVerwaltung::Initial() {
    return Transpo;
}

Or, just move the array into global scope, eg:

CTransponder Transpo[10] = {
    CTransponder("Chef", 100),
    CTransponder("Chefin", 101),
    ...
};

std::vector<CTransponder> CVerwaltung::Initial(){
    return Transpo;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[3] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...