Overall, or this specific case?
In this case,
std::string::c_str
The pointer returned may be invalidated by further calls to other member functions that modify the object. |
const char** com = new const char* {command.c_str()};
is practically same as
1 2
|
const char* tmp = command.c_str();
const char** com = new const char* {tmp};
|
The c_str() returns a pointer to const. The tmp is a copy of that.
The dynamically allocated pointer is a copy of that
The automatic variable (pointer com) points to the dynamically allocated pointer.
However, if you call members of command, the *com might not be valid any more.
Perhaps:
const char* gaz = new const char { command.c_str()[0] };
No problem there. the gaz points to
a char that was (1) dynamically allocated and (2) was initialized with the first character of 'command'.
In other words: yes, you can allocate const memory. Like any const objects you have to initialize it, for you cannot assign value to it later.
You can even allocate an array of const:
1 2 3 4 5 6
|
#include <iostream>
int main ()
{
const char* gaz = new const char [6] {'h', 'e', 'l', 'l', 'o', 0 };
std::cout << gaz;
}
|
Alas, initializing that array with a pointer is not possible.
Furthermore, the "const new" is nominal:
1 2 3 4 5 6 7 8 9
|
#include <iostream>
int main ()
{
const char* gaz = new const char [6] {'h', 'e', 'l', 'l', 'o', 0 };
char* bar = const_cast<char*>(gaz);
bar[0] = 'D';
std::cout << gaz;
}
|
Dello |