+ 1
how to avoid warning in my own stack template
Hi I have tried to implement stack class as template type as below: https://code.sololearn.com/cy3PSIom22ft I am getting warning on the code for char* using on my stack implementation. Need your suggestion on the same in order to avoid warning. Thanks in advance...!
5 ответов
+ 2
Declaration of stack s
mystack<const char*> s;
change the static_casts to
static_cast<const char*>
Alternatively you can use
const_cast<char*> instead of static_cast
+ 1
String literals are immutable so I believe the warnings here are useful.
You could use const_cast<type>(arg) to cast away the constness but I would advice against it. String literals are read-only and if they're modified the program will probably crash (or evoke undefined behavior).
The danger is that you could do something like this:
char *a = s.top()
*a = 'C';
If the stack accepts <const char *> the static casts are not needed, the warnings will go away and the compiler will complain if you try to modify the strings or assign them to a mutable datatype.
+ 1
Both the option worked... I am confused now on immutable..
I generally used to modify the string as below:
string s = "welcome ";
string name = "Ketan";
s += name;
cout << s;
Isn't it good ? If so, what's best to do same?
+ 1
Ketan Lalcheta
Yes that's fine. std::string is mutable because it copies the string literal into an internal buffer. "string literal" <-- like that one, is a const char * and is not mutable.
I think the confusion is due to the difference between char *, const char *, and std::string.
0
Okay Gen2oo , I updated and removed costantness by using const_cast while adding to stack...
Reason of same is that I wanted to allocate the memory in case of pointer data type...
However , I got confused with how to allocate memory...
template<typename T>
node<T>::node(T idata)
{
if(is_pointer<T>::value)
{
data = new static_cast<*T>;
}
data = idata;
}
I thought to add parametric constructor for node data addition. But how to do new operator is confusing me