0

I have found a lot of examples from stack overflow, but those examples are based on non-const std::string. What if the string is const(top level and non top level)?

std::string encrypt(std::string const &input)
{
  //do something, ArrayGuard is a smart pointer to guard the raw char* delete by free
  ArrayGuard<char> guard(encrypt_str(const_cast<char*>(input.c_str())));

  return std::string(guard.get(), std::strlen(guard.get()));    
}

case 1(non top level?) :

std::string input = "abcde";
std::string encrypt_password = encrypt(input);

case 2(top level?) :

std::string const input = "abcde";
std::string encrypt_password = encrypt(input);

I am sure that the encrypt_str would not alter the char* I pass into it(if it is possible, I would like to ask them to fix this non const correction api).

ps : I am not sure that I am fully understanding what is top level const/&/&&/volatile, that is why I put "?" behind the case

user3689849
  • 521
  • 1
  • 3
  • 14

1 Answers1

2

The rule you have to watch out for regarding const_cast is that if you use it to modify an object that was originally declared as const, then you get undefined behaviour.

As long as you're sure this doesn't happen, you're good.

The constness of the std::string doesn't make any difference. Even if the std::string is not const, the c_str function still returns a const char*. Nothing changes when you make the std::string const.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • Agree on the first count, not so much in the second. Whether the original object is const or not matters for the case where you want to attempt a modification. The `c_str()` return a `const char*`, but that does not mean that it points to a `const char` (it can point to a non-const char). – David Rodríguez - dribeas Jun 19 '14 at 03:29
  • @DavidRodríguez-dribeas Yes, I agree. The last paragraph is written with the assumption that the `encrypt_str` function really does not modify the string. – Brian Bi Jun 19 '14 at 03:32
  • @DavidRodríguez-dribeas You are not allowed to try to modify the character pointed-to by `c_str()`. Even if it happens physically to point to a non-const char, you must treat it as a const char. For example, two strings might share storage, so modifying the character corrupts an unrelated string. – Raymond Chen Jun 19 '14 at 03:58
  • @raymond: aren't COW strings forbidden in c++11? [you are right that without context I should not assume that, specially since a common implementation still does COW --gcc] – David Rodríguez - dribeas Jun 19 '14 at 04:00
  • 1
    @DavidRodríguez-dribeas There's no point discussing what an implementation might do. Writing to the pointer returned by `c_str()` invokes UB. (Theoretically, an implementation could copy the string to a new block of memory, write-protect that memory, then return that memory from `c_str()`, and if a write protect exception occurs, it reformats your hard drive.) – Raymond Chen Jun 19 '14 at 06:58