Welcome to OStack Knowledge Sharing 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 Answer

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...