Pedro
Pedro

Reputation: 4160

C++ returning stringstream.str()

I have a static method that should return the next available id. Several static members in other classes call this function, so each gets a different id assigned. However, when I am printing the assigned values I dont get "id0", "id1" but just a symbol like "*". I'm using this code:

    int A::i = 0; //static member

std::string A::id()
{
    std::stringstream sst; 
    sst<< "id" << A::i;

    i++;

    return sst.str(); //i've tried to return a const char* too, but doesnt work either
}


   //assigning id's in several classes like this: 
   const char* B::id = A::id().c_str(); 
   const char* C::id = A::id().c_str(); 


   //printing them in the main function: 
   std::cout << B::id << " " << C::id << "\n";

I dont understand why the code above doesnt work. When I am executing the following code the expected result "id10" is printed:

    static std::string  gt()
    {
         std::stringstream ss; 
         ss << "id" << 10;

         return ss.str();
    }

Upvotes: 1

Views: 4106

Answers (1)

K-ballo
K-ballo

Reputation: 81349

Look at

const char* C::id = A::id().c_str(); 

You are creating a new id string, then you take a pointer to its data (as a c-string), and inmediately after that the temporary string to which contents you are pointing gets destroyed. Simple answer: either stick to std::string or to plain int ids.

Upvotes: 6

Related Questions