c++ std::string assign fail

Russian translation below.

Hi there!

Small error that you can create using C++ string assign.
See code below.

It seems, that such code should work correctly. But '\0' symbol play joke in here.
If you see method description c plus plus string assign:
You will find:

string& assign ( const string& str, size_t pos, size_t n );
but not!
string& assign ( const char* str, size_t pos, size_t n );

This is the place where std::string constructor going to be called. And this is a place where char p[] going to be сutted.
And as result, you will get an exception.

Just try a.assign(p + 7, 7) instead.



Всем привет!

небольшой прикол по поводу std::string::assign
Код чуть ниже.
Казалось бы, что может быть безобиднее присвоения части строки содержащей '\0'? Вроде всё верно - и её не должно задеть.
Однако сигнатура метода c plus plus string assign:

string& assign ( const string& str, size_t pos, size_t n );
а никак не
string& assign ( const char* str, size_t pos, size_t n );

и в данном месте у нас появляется неявный вызов конструктора - который успешно уменьшает строку, ну и результат дальше предсказуем.

Решением будет a.assign(p + 7, 7).


int main()
{
 char p[] = "world\0 to you";
 std::string a = "hello ";
 try
 {
  a.assign(p, 7, 7);
  std::cout << a.c_str() << std::endl;
 }
 catch(const std::exception& ex)
 {
  std::cout << ex.what() << std::endl;
 }

 return 0;
}

0 комментария(ев):