473,386 Members | 1,609 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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<vector<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(vector<string>& sequence);
vector<string> rearrange(vector<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<vector<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;
}

-- lovecreatesbeauty

Aug 25 '05 #1
11 5233
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(vector<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(vector<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<vector<string> >(sequence); // #4 error.

// ...

}

Aug 25 '05 #3
Ian
lovecreatesbeauty 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
lovecreatesbeauty 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<vector<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

lovecreatesbeauty 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<vector<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(vector<string>& sequence);
vector<string> rearrange(vector<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<vector<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;
}

-- lovecreatesbeauty


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
lovecreatesbeauty 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
In message <11**********************@f14g2000cwb.googlegroups .com>,
an****************@gmail.com writes
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?


If the object to which it points was originally declared const, on some
platforms the compiler might for instance allocate it in read-only
memory.

const T thing; // not legally modifiable
T * p = const_cast<T*>(&thing);
p->Modify(); // UB

If you're merely casting away a const that was added by an earlier cast,
there's no problem:

T thing; // modifiable
const T * p = &thing; // not modifiable via this pointer
T * q = const_cast<T*>(p); // cast away the const added by p
q->Modify(); // no problem, the original thing was non-const.

--
Richard Herring
Aug 31 '05 #11
"lovecreatesbeauty" <lo***************@gmail.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
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
Umm..what's wrong with:
Type * ptr = cptr;
const Type ct = Type();
Type t = const_cast<Type>(ct); // #2 error
Type t = ct;
const vector<Type> cv;
vector<Type> v = const_cast<vector<Type> >(cv); // 3# error
vector<Type> v = cv;
}


I think you're getting a little confused as to what that const keyword is
actually doing. The const keywords means you can't change THAT variable.
Not that you can't READ from it.
Sep 3 '05 #12

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

Similar topics

2
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...
8
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,...
6
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...
5
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
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...
10
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...
13
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
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
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...
56
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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,...

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.