This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Map to const.

Tags: None
(comma "," separated)
rafaelrojas
Registered Member
Posts
5
Karma
0

Map to const.

Tue Feb 17, 2015 6:00 pm
The following code works:

Code: Select all
double ptr1[9]={1,2,3,4,5,6,7,8,9};
const double ptr2[9]={1,2,3,4,5,6,7,8,9};
Map<Matrix<double,3,3> >    mUseless(ptr1);
new (&mUseless) Map<const Matrix<double,3,3> > (ptr2);
mUseless(1,1)=6.0;


why??
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Map to const.  Topic is solved

Tue Feb 17, 2015 9:19 pm
Calling placement new does not change the type of the object, and since mUseless is not a const Map, it is perfectly normal that you can change the object. Your code is similar to a reinterpret_cast from a Map<const Matrix<double,3,3> > to a Map<Matrix<double,3,3> >.
rafaelrojas
Registered Member
Posts
5
Karma
0

Re: Map to const.

Wed Feb 18, 2015 10:04 am
So how may I protect a Map from writing?? I'm using the same map for several operatation with raw buffers. Some of
those buffers are const. It is mandatory to use specially a new Map<const Type > to work with const arrays? or there
is another way to implement a single map to work with both const and not const in a secure way??

And there is not a way to forbid the "new (&,mUseless) Map<const Matrix<double,3,3> >" statements when mUseless is
not a map to const??
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Map to const.

Wed Feb 18, 2015 2:32 pm
You can use const map even to map non const pointers:

Map<const Matrix<double,3,3> > mUseless(ptr1);

In which case mUseless(1,1)= blabla; will be forbidden regardless of the constness of the input pointer. But in C++ an object cannot change its constness at runtime!


Bookmarks



Who is online

Registered users: Bing [Bot], Google [Bot], Yahoo [Bot]