dimanche 21 juin 2020

String as member of container which is a member of a C++ class

I have a class that has a set member variable. This set is going to hold a bunch of std::strings which are added to it throughout the life of the object.

The strings are passed in from a calling function (they are created in the calling function). My understanding is that in C++ string objects have their destructors called as soon as they leave scope. So if I understand correctly, when the calling method which created the string exits scope, the destructor should be called. Likewise, even if I make a copy of the string in the method in my class, it would still be destroyed when out of scope. However, I want the string to live in the Set for the life of the object.

What is the proper way to do this in C++? Should the string just be allocated on the heap through new and then destroyed manually?

#include <set>
#include <string>

class Foo
{
    private:
        set<string> myStrings;
        
    public:
        void DoSomething(string s);
}

Foo::DoSomething(string s)
{
    myStrings.insert(s);
} // s would be destroyed here?

Aucun commentaire:

Enregistrer un commentaire