Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When working with a C API, use character arrays or use strings and convert as needed?

Tags:

c++

arrays

string

I'm working with a C API and a lot of the functions take arguments that are character arrays. I've heard that using char arrays is now frowned upon. But on the other hand, using c_str() to convert the string to a char array over-and-over seems wasteful.

Are there any reasons to do it one way vs the other?

like image 814
Jcrack Avatar asked Dec 04 '22 05:12

Jcrack


1 Answers

The c_str() call is quite likely to be inlined—it's very small in terms of the required code. I would use std::string if that's the only thing holding you back.

Of course, if you're very worried, this standard advice applies:

  1. Profile it
  2. Read the assembly

Also be aware that this is a micro-optimization; you're quite likely to be wasting development time worrying about something completely different than from what you should be worrying about.

like image 160
unwind Avatar answered Feb 18 '23 07:02

unwind