How to cast away the volatile-ness? Which c++ style cast should I use?
Asked
Active
Viewed 1.5k times
1 Answers
63
Use const_cast
.
For example,
volatile sample *pvs = new sample();
sample *ps = const_cast<sample*>(pvs); //casting away the volatile-ness
That is, const_cast
is used to cast away both const-ness as well as volatile-ness. Unfortunately, its name doesn't contain the term "volatile". Maybe, that is because the keyword const
is more common in use than the keyword volatile
. As one of the comment says, cv_cast
would have been more appropriate name!

Nawaz
- 353,942
- 115
- 666
- 851
-
19they should call it cv_cast or something, then. – Jason S Mar 09 '11 at 17:44
-
3@Jason: That looks good. After all, C++ Standard often uses `cv` to mean const-volatile! – Nawaz Mar 09 '11 at 17:47
-
@Mehrdad: I think `const-ness` is better than `constancy`. It points to a *particular* language keyword. Also, C++ programmers use it that way. So I'm thinking of rollback. Do you agree? – Nawaz Mar 09 '11 at 18:22
-
@Nawaz: Hm... sure, okay, roll it back then. Both have their upsides. :) – user541686 Mar 09 '11 at 18:23
-
@Nawaz: Haha no problem; it makes the post better and that's what really matters. I didn't really give my edit a second thought. :) – user541686 Mar 09 '11 at 18:28
-
Is there an equivalent for `const_cast` in C ? – Bionix1441 Jul 14 '15 at 07:45
-
1@Bionix1441: Use : `T * x = (T*)(obj);` syntax which you use for all kind of cast. – Nawaz Jul 14 '15 at 07:50
-
1In C++ you shouldn't use C-like casts - i.e. (T*)obj - cause every cast type would be tried, event if you only want one special (and otherwise the compiler should terminate with an error) – Traummaennlein Feb 09 '18 at 10:39
-
@Bionix1441 there is no C cast that *only* does what `const_cast` does. The reason C++ added the `_cast`s was because C style casts did too many things with the same syntax. – Caleth Jul 20 '18 at 09:08
-
1@Caleth: Also, C-style cast **cannot** do what `dynamic_cast` does, so C++ added this! – Nawaz Jul 20 '18 at 09:15