-Поиск по дневнику

Поиск сообщений в rss_thedaily_wtf

 -Подписка по e-mail

 

 -Постоянные читатели

 -Статистика

Статистика LiveInternet.ru: показано количество хитов и посетителей
Создан: 06.04.2008
Записей:
Комментариев:
Написано: 0


CodeSOD: unstd::toupper

Вторник, 13 Сентября 2016 г. 13:30 + в цитатник

C++ is a language with a… checkered past. Its grown, matured and changed over the decades, and modern C++ looks very little like the C++ of yesteryear. Standard libraries have grown and improved- these days, std feels nearly as big and complicated as parts of Javas class library.

One useful function is std::toupper. Given a char, it will turn that char into an upper-case version, in a locale-aware fashion. What if you want to turn an entire string to upper-case?

You might be tempted to use a function like std::transform, which is C++s version of map. It alters the string in-place, turning it into an upper-cased version. With a single line of code, you could easily convert strings to upper-case.

Or, you could do what Tomeks highly-paid consultant did.

std::string toupper(std::string val)
{
    std::string out;
    if (val.empty())
        return "";
    std::for_each(val.begin(), val.end(), std::toupper);
    return out;
}

Like a true highly-paid consultant, the developer knew that programmer time is more expensive than memory or CPU time, so instead of wasting keystrokes passing the input as a const-reference, they passed by value. Sure, that means every time this function is called, the string must be copied in its entirety, but think of the developer productivity gains!

Its always important to be a defensive programmer, so in true consultant fashion, well check to ensure that the input string isnt already empty. Of course, since we manipulate the string with std::for_each, we dont actually need that check, its better to be explicit.

Speaking of for_each, it has one advantage over transform- it wont modify the string in place. In fact, it wont modify the string at all, at least as written here. Everyone knows immutable objects cut down on many common bugs, so this is an excellent design choice.

And finally, they return out, the string variable declared at the top of the function, and never initialized. This, of course, is because while your requirements said you needed to turn strings into fully upper-case versions, you dont actually need that. This is a better solution thats more suited to your business needs.

[Advertisement] Otter, ProGet, BuildMaster – robust, powerful, scalable, and reliable additions to your existing DevOps toolchain.

http://thedailywtf.com/articles/unstd-toupper

Метки:  

 

Добавить комментарий:
Текст комментария: смайлики

Проверка орфографии: (найти ошибки)

Прикрепить картинку:

 Переводить URL в ссылку
 Подписаться на комментарии
 Подписать картинку