I want to expand std :: string, but not for the reason

I have a method that efficiently takes a string. However, there is a very limited subset of strings that I want to use. I thought of typedef'ing std :: string as some class and called functions explicit. However, I am not sure if this will work. Ideas?

+3
source share
3 answers

The usual rule still applies: the class is not intended to be inherited, and its destructor is not virtual, so if you ever raise the std :: string base class and let the object be destroyed, your derived destructor class will not be called.

, , .

std::string , . . , .

, getString(), std::string. , , std::string, , . .

+8

, (, , ).

, .

class limited_string
{
    std::string str;

public:
    limited_string(const char *data)
        : str(data)
    {
        if (!valid(str))
            throw std::runtime_exception(); 
    }

    virtual ~limited_string() {}

    limited_string &operator+=(const char *data)
    {
        // do all your work on the side - this way you don't have to rollback
        // if the newly created string is invalid
        std::string newstr(str);
        newstr += data;
        if (!valid(newstr))
            throw std::runtime_exception();

        str = newstr;
    }

    virtual bool valid(const std::string str) = 0;
}
+7

, , . ?

void needs_restricted_string( std::string const &str ) {
    if ( ! is_restricted_string( str ) ) throw std::runtime_error( "bad str" );
}

, , , . , is_restricted_string() , - , , . . , .

class restricted_string {
    std::string storage;
public:
     // constructor may implement move or swap() semantics for performance
     // it throws if string is no good
     // not explicit, may be called for implicit conversion
    restricted_string( std::string const & ) throw runtime_error;
     // getter should perhaps be private with needs_restricted as friend
    std::string const &str() const { return storage; }
}; // and no more functionality than that!

void needs_restricted_string( restricted_string const &str ) {
    std::string const &known_restricted = str.str();
}

std::string mystr( "hello" );
needs_restricted_string( mystr );
0

Source: https://habr.com/ru/post/1737590/


All Articles