std::string += operator cannot pass 0 as argument

The problem is that a literal 0 is a null pointer constant. The compiler doesn’t know if you meant: std::string::operator +=(const char*); // tmp += “abc”; or std::string::operator +=(char); // tmp += ‘a’; (better compilers list the options). The workround (as you have discovered) is to write the append as: tmp += ‘\0’; (I assume … Read more

Does “&s[0]” point to contiguous characters in a std::string?

A std::string’s allocation is not guaranteed to be contiguous under the C++98/03 standard, but C++11 forces it to be. In practice, neither I nor Herb Sutter know of an implementation that does not use contiguous storage. Notice that the &s[0] thing is always guaranteed to work by the C++11 standard, even in the 0-length string … Read more

Append int to std::string

TL;DR operator+= is a class member function in class string, while operator+ is a template function. The standard class template<typename CharT> basic_string<CharT> has overloaded function basic_string& operator+=(CharT), and string is just basic_string<char>. As values that fits in a lower type can be automatically cast into that type, in expression s += 2, the 2 is … Read more

Why is initializing a string to “” more efficient than the default constructor?

This is an intentional decision in libc++’s implementation of std::string. First of all, std::string has so-called Small String Optimization (SSO), which means that for very short (or empty) strings, it will store their contents directly inside of the container, rather than allocating dynamic memory. That’s why we don’t see any allocations in either case. In … Read more

Remove First and Last Character C++

Well, you could erase() the first character too (note that erase() modifies the string): m_VirtualHostName.erase(0, 1); m_VirtualHostName.erase(m_VirtualHostName.size() – 1); But in this case, a simpler way is to take a substring: m_VirtualHostName = m_VirtualHostName.substr(1, m_VirtualHostName.size() – 2); Be careful to validate that the string actually has at least two characters in it first…

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

Consider this: std::string str = “Hello ” + “world”; // bad! Both the rhs and the lhs for operator + are char*s. There is no definition of operator + that takes two char*s (in fact, the language doesn’t permit you to write one). As a result, on my compiler this produces a “cannot add two … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)