I understand that using std::string_view is better than std::string because it allows const char* and std::string values to be passed without needing a std::string object to be created.
Also i understand the it provides a ReadOnly access
However, i was wondering if it is a good practice to define a public std:string_view variable and update it through the class constructor.
i.e:
What is the difference between test1 and test2, assuming test1 or test2 is defined in a library class which can be instantiated by different clients.
class test1{
public:
std::string_view name_;
test1 (std::string_view name): name_ {name} {};
void print() {
cout<<"test1 "<<name_<<endl;
}
};
class test2{
public:
std::string name_;
test2 (std::string_view name): name_ {name} {};
void print() {
cout<<"test2 "<<name_<<endl;
}
};
While it's not wrong as such, it's potentially unsafe. It's extremely important for the user of the class to understand that the member will remain valid only as long as the pointed string's lifetime, which may be shorter than that of the object. It should be both documented clearly, and the name of the class should reflect its referential nature. Some examples are suffixes such as
_viewor_ref.The class
test1won't be useful in such cases where the lifetime must be longer than that of the pointed string. This consideration is same as when using a member of typeconst char*.