473,898 Members | 2,542 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can I remove constant from non-pointer variables

Hello experts,

Is const_cast only applied to pointers or references? If I have a
constant object, then how can I remove constant attribute from it?
#include <vector>
#include <string>
using namespace std;

class Type{
};

int main(int argc, char * argv[]){

const Type * cptr = 0;
Type * ptr = const_cast<Type *>(cptr); // #1 ok

const Type ct = Type();
Type t = const_cast<Type >(ct); // #2 error

const vector<Type> cv;
vector<Type> v = const_cast<vect or<Type> >(cv); // 3# error
}


And suppose I have a function as follows, how can I remove the constant
from the parameter with type of
const vector<string>& sequence, or
const vector<string> sequence?

Could you please give me more suggestions on the declaration of this
function (or even all my code, thanks). Is it better for me to change
its declaration to some other formats? For example, may I declare it
one of the following:

vector<string> & rearrange(vecto r<string>& sequence);
vector<string> rearrange(vecto r<string> sequence);
vector<string> & rearrange(const vector<string>& sequence);
vector<string> rearrange(const vector<string> sequence);

vector<string> rearrange(const vector<string>& sequence){
vector<string> vecTmp = sequence;

// vector<string> vecTmp =
// const_cast<vect or<string> >(sequence); // #4 error
int iSeqWth = vecTmp.size();
string strSwp;

for (int i = 0; i < iSeqWth; ++i){
for (int j = i + 1; j < iSeqWth; ++j){
if (atoi(vecTmp[i].c_str()) > atoi(vecTmp[j].c_str())){
strSwp = vecTmp[i];
vecTmp[i] = vecTmp[j];
vecTmp[j] = strSwp;
}
}
}

return vecTmp;
}

-- lovecreatesbeau ty

Aug 25 '05 #1
11 5315
Hi

You really shouldn't try to "remove the constant".
Things are declared constant, because they shouldn't be modified.

The const_cast operator cannot be used to directly override a
variable's constant status. Yes, it only works with pointers.

It should also be noted, that using the resulting pointer (from the
const_cast operator) to perform write operations might result in
undefined behavior.

About your rearrange/sorting function:
Parameters can be passed by reference or by value.
A parameter passed by reference, gives you a reference to the original
value and changing the parameter would result in changing the original
value.
A parameter passed by value, gives you a copy of the original and
changes on the parameter wouldn't effect the original (given that the
copy constructor and assignment operator where implemented correctly).

If you intend to sort the original vector, declare the function as
void rearrange(vecto r<string>& p_vec)
{
// sorting login in here
// no return statement needed
}
Should you intend to sort a copy of the original vector, you could
declare the function as:
vector<string> rearrange(vecto r<string> p_vec)
{
// sorting login in here
return p_vec;
}

Alternatively on can do what you've already done
vector<string> rearrange(const vector<string> p_vec)
{
// create a copy of p_vec
// sort the copy
// return the copy
}

Joe

Aug 25 '05 #2
Thanks. But there is a conversion from const to non-const in my code
without the C++ standard compliant explicit conversion. It is:

vector<string> rearrange(const vector<string>& sequence){
vector<string> vecTmp = sequence; //
non-standard conversion! so I want to enforce the standard explicit

// conversion on it as following, but failed.

// vector<string> vecTmp =
// const_cast<vect or<string> >(sequence); // #4 error.

// ...

}

Aug 25 '05 #3
Ian
lovecreatesbeau ty wrote:
Hello experts,

Is const_cast only applied to pointers or references? If I have a
constant object, then how can I remove constant attribute from it?

Why on earth would you want to?

const is there for a reason!

Ian
Aug 25 '05 #4
Ian
lovecreatesbeau ty wrote:
Thanks. But there is a conversion from const to non-const in my code
without the C++ standard compliant explicit conversion. It is:

vector<string> rearrange(const vector<string>& sequence){
vector<string> vecTmp = sequence; //
non-standard conversion! so I want to enforce the standard explicit

// conversion on it as following, but failed.

// vector<string> vecTmp =
// const_cast<vect or<string> >(sequence); // #4 error.

// ...

}

why not

vector<string> vecTmp( sequence.begin( ), sequence.end() );

Ian
Aug 25 '05 #5
>>vector<string > rearrange(const vector<string>& sequence){
vector<string> vecTmp = sequence; //
non-standard conversion! so I want to enforce the standard explicit

const means you can't change me., it doesn't mean you can't read me. No
conversion is taking place here. You are simply copying the
value/contents of a const object into a non-const object. which is
absolutely right.

To copy the value from a const object, we don't need const_cast<>
..Instead purpose of const_cast is to modify the object contents by
removing the const qualifier temprorily. const Type * cptr = 0;
Type * ptr = const_cast<Type *>(cptr);

Here you are removing const qualifier using const_cast<>, so that your
const Type * is now Type *, and ptr is just pointing to your original
object which value you can modify through ptr.

class Type{
public: int i;
Type(int j):i(j){}
};
int main(int argc, char * argv[]){

const Type * cptr = new Type(20);
cout<<cptr->i<<endl;;
const_cast<Type *>(cptr)->i=10; <<<<<<<<<
cout<<cptr->i<<endl;
}
Remember:
1. a write operation through the resulting pointer, reference, or
pointer to data member might produce undefined behavior.
2. You cannot use the const_cast operator to directly override a
constant variable's constant status.

Aug 25 '05 #6
Along with the reasonings given above, const_cast is mainly used during
parameter passing to, say, legacy routines. Legacy code might not take
const references or pointers. In such cases, user code today, might
need to use const_cast on the parameters. If a function is taking an
object and not a reference or a pointer as its argument, what the
function would get is anyway a copy of the object. Changes to the
object made in the function would not be reflected in the caller's
object.

// some function
voif fun(Type obj)
{
// ...
}

// user code
const Type obj;
fun(obj);

Here, obj is being passed by value and const_cast is not required
anyway. Its known that const_cast cannot be applied on objects
themselves. I am trying to convey that most of the times its
unnecessary and does not make sense to use const_cast on objects.

Srini

Aug 25 '05 #7

lovecreatesbeau ty wrote:
Hello experts,

Is const_cast only applied to pointers or references? If I have a
constant object, then how can I remove constant attribute from it?
#include <vector>
#include <string>
using namespace std;

class Type{
};

int main(int argc, char * argv[]){

const Type * cptr = 0;
Type * ptr = const_cast<Type *>(cptr); // #1 ok

const Type ct = Type();
Type t = const_cast<Type >(ct); // #2 error

const vector<Type> cv;
vector<Type> v = const_cast<vect or<Type> >(cv); // 3# error
}


And suppose I have a function as follows, how can I remove the constant
from the parameter with type of
const vector<string>& sequence, or
const vector<string> sequence?

Could you please give me more suggestions on the declaration of this
function (or even all my code, thanks). Is it better for me to change
its declaration to some other formats? For example, may I declare it
one of the following:

vector<string> & rearrange(vecto r<string>& sequence);
vector<string> rearrange(vecto r<string> sequence);
vector<string> & rearrange(const vector<string>& sequence);
vector<string> rearrange(const vector<string> sequence);

vector<string> rearrange(const vector<string>& sequence){
vector<string> vecTmp = sequence;

// vector<string> vecTmp =
// const_cast<vect or<string> >(sequence); // #4 error
int iSeqWth = vecTmp.size();
string strSwp;

for (int i = 0; i < iSeqWth; ++i){
for (int j = i + 1; j < iSeqWth; ++j){
if (atoi(vecTmp[i].c_str()) > atoi(vecTmp[j].c_str())){
strSwp = vecTmp[i];
vecTmp[i] = vecTmp[j];
vecTmp[j] = strSwp;
}
}
}

return vecTmp;
}

-- lovecreatesbeau ty


Actually, removing the const from a declaration is not all that
difficult. Though even experts have been tripped up from time to time.
Here, i will demonstrate the proper procedure.

Before:

const vector<string> sequence;

After:

vector<string> sequence;

The const portion of the declaration has been successfully removed; now
the sequence variable can be used in a non-const manner.

Next week, I will be demonstrating a similar procedure for "volatile"
declarations which you won't want to miss.

Greg

ps. in all seriousness, there is no other way to "remove" a constness
from a declaration. Either the variable is declared const or it is not
(or course if non-const it can still be made available to a function
only in a const form).

Aug 26 '05 #8
lovecreatesbeau ty wrote:
vector<string> rearrange(const vector<string> sequence);


I think such a parameter declaration adds no value. What
is the point in making it const in the above case?
Anybody?

void g(const T& t);
void g(T& t);
void g(T t);
void g(const T t); // const adds no value

Rgds,
anna

Aug 26 '05 #9
jo*****@dariel. co.za wrote:
It should also be noted, that using the resulting pointer (from the
const_cast operator) to perform write operations might result in
undefined behavior.


*might* means?

Rgds,
anna

Aug 26 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
6528
by: srinivas reddy | last post by:
Hi, Can a constant member function be overloaded with its non-constant equivalent. I mean can void func() be overloaded with void func() const. If so what behaviour is guaranteed, how does the compiler resolve ambiguity?, and how could I call a specific variant? tia, Srinivas
8
3160
by: Tony Johansson | last post by:
Hello Experts! What does this mean actually. If you have a template with a type and non-type template argument, say, like this template<typename T, int a> class Array {. . .}; then A<int, 1> and A<int, 2> are different types. Now, if the A template
6
2841
by: niklaus | last post by:
Hi, I have seen that the following code compiles in some environments like devc++ but fails on some env's like gcc on linux. Can someone tell if "int *au=malloc(sizeof(int)*10);" is a constant expression and can be used in global namespace/file scope. Which part of the standard says or describes this . #include<stdio.h> #include<stdlib.h>
5
1848
by: Joyti | last post by:
Hi, Need help in solving issue. I m having one function: int alllowReset(TRAN & tranP) { if( tranP->name == "PQRS" || ... ..
10
9488
by: Steve Pope | last post by:
The first of the following functions compiles, the second gives what I think is a spurious error: "cannot convert `const char' to `char *' in assignment". void foo(int m) { char *str; if (m < 4) str = "%01x"; else if (m < 9) str = "%02x"; else str = "%03x";
10
6781
by: pamelafluente | last post by:
Hi I have a sorted list with several thousands items. In my case, but this is not important, objects are stored only in Keys, Values are all Nothing. Several of the stored objects (might be a large number) have to be removed (say when ToBeRemoved = true). class SomeObj ToBeRemoved be a boolean field end class
13
27458
by: hn.ft.pris | last post by:
Hi: I have the following simple program: #include<iostream> using namespace std; int main(int argc, char* argv){ const double L = 1.234; const int T = static_cast<const int>(L); int arr;
18
1941
by: sinbad | last post by:
hi, why does the following program gives an runtime error ,instead of compilation error. anyone please shed some light. thanks sinbad ------------------------------ int main()
22
3634
by: Tomás Ó hÉilidhe | last post by:
I've been developing a C89 microcontroller application for a while now and I've been testing its compilation using gcc. I've gotten zero errors and zero warnings with gcc, but now that I've moved over to the micrcontroller compiler I'm getting all sorts of errors. One thing I'd like to clarify is the need (in C89) for a compile- time constant in the initialiser of a variable. The compiler rejects the following source file: /* Start...
56
6801
by: Adem | last post by:
C/C++ language proposal: Change the 'case expression' from "integral constant-expression" to "integral expression" The C++ Standard (ISO/IEC 14882, Second edition, 2003-10-15) says under 6.4.2(2) : case constant-expression : I propose that the case expression of the switch statement be changed from "integral constant-expression" to "integral expression".
0
9839
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11254
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10480
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9658
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7187
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6076
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4701
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4295
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3303
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.