473,573 Members | 2,920 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How bad is making a field mutable?

I wrote a dynamic matrix class similar to the one described in TCPL 3rd
Edition. Rather than define two separate iterators for const and non-const
scenarios I decided to be a lazy bastard and only have one and make the data
representation (a std::valarray) mutable instead. My question is, how bad is
that? Am I running the risk of undefined behaviour, or is the worst case
scenario simply const violation?

--
Christopher Diggins
http://www.cdiggins.com
Jul 23 '05 #1
6 1731
* christopher diggins:
I wrote a dynamic matrix class similar to the one described in TCPL 3rd
Edition. Rather than define two separate iterators for const and non-const
scenarios I decided to be a lazy bastard and only have one and make the data
representation (a std::valarray) mutable instead. My question is, how bad is
that? Am I running the risk of undefined behaviour
Probably, if it's possible to originally declare a matrix with non-zero
size as constant.

Matrix<int> const m(2, 2);

*m.begin() = 1; // Probably compiles but UB.

or is the worst case scenario simply const violation?


Depends.

Const violation for an object originally declared const is UB.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #2
On 2005-06-03, christopher diggins <cd******@video tron.ca> wrote:
I wrote a dynamic matrix class similar to the one described in TCPL 3rd
Edition. Rather than define two separate iterators for const and non-const
scenarios I decided to be a lazy bastard
So far so good. Laziness is good.
and only have one and make the data
representation (a std::valarray) mutable instead.
No. Bad.

The smart way to be lazy would be to make your iterator a template class.

template <typename T, typename pointer> general_iterato r {
....
};

typedef general_iterato r<T,T*> iterator;
typedef general_iterato r<T,const T*> const_iterator;
My question is, how bad is that?
Very bad.
Am I running the risk of undefined behaviour,
Probably depends on what you do with it. One case where it gets you in a
lot of trouble is with threaded code. Modifying state behind the clients
back means that methods that look like they shouldn't require an exclusive
lock actually do require one. For example, it's reasonable to expect that
multiple concurrent readers are OK, but if those readers are secretly
writing, then it's a problem. I suppose you could require that every element
access of any kind required an exclusive lock, but I'm sure you can see why
that's unwieldy.
or is the worst case scenario simply const violation?


const violation is already very bad. It makes life very inconvenient when you
get bugs, because you can no longer trust the word "const" any more. "const"
is a contract of sorts. When you stop honoring it, it loses its relevance.

Cheers,
--
Donovan Rebbechi
http://pegasus.rutgers.edu/~elflord/
Jul 23 '05 #3
"Alf P. Steinbach" <al***@start.no > wrote in message
news:42******** *********@news. individual.net. ..
* christopher diggins:
I wrote a dynamic matrix class similar to the one described in TCPL 3rd
Edition. Rather than define two separate iterators for const and
non-const
scenarios I decided to be a lazy bastard and only have one and make the
data
representation (a std::valarray) mutable instead. My question is, how bad
is
that? Am I running the risk of undefined behaviour


Probably, if it's possible to originally declare a matrix with non-zero
size as constant.

Matrix<int> const m(2, 2);

*m.begin() = 1; // Probably compiles but UB.


So I have this:

template<typena me T>
class Matrix {
mutable std::valarray<T > m;
public:
Matrix(int rows, int cols) : m(rows * cols) { }
T* begin() const { return &m[0]; }
...
}

Why does this lead to undefined behaviour? By stating that m is mutable,
does it not tell the compiler that m can be changed? If I understand you
correctly would this not mean that any modification of a mutable variable by
a const function is UB?

I am perhaps confused.

Thanks for your help!

--
Christopher Diggins
http://www.cdiggins.com
Jul 23 '05 #4
* christopher diggins:

Why does this lead to undefined behaviour? By stating that m is mutable,
does it not tell the compiler that m can be changed? If I understand you
correctly would this not mean that any modification of a mutable variable by
a const function is UB?
You're right, sorry.

Reference:

§7.1.5.1/4 states that "Except that any class member declared 'mutable' can
be modified, any attempt to modify a 'const' object during its lifetime
results in undefined behavior".

I am perhaps confused.

Thanks for your help!


Well, it was less than nothing, so thanks for the thanks!

But, anyway, consider not breaking constness.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #5
"Donovan Rebbechi" <ab***@aol.co m> wrote in message
news:sl******** **********@pani x2.panix.com...
On 2005-06-03, christopher diggins <cd******@video tron.ca> wrote:
I wrote a dynamic matrix class similar to the one described in TCPL 3rd
Edition. Rather than define two separate iterators for const and
non-const
scenarios I decided to be a lazy bastard


So far so good. Laziness is good.
and only have one and make the data
representation (a std::valarray) mutable instead.


No. Bad.

The smart way to be lazy would be to make your iterator a template class.

template <typename T, typename pointer> general_iterato r {
...
};

typedef general_iterato r<T,T*> iterator;
typedef general_iterato r<T,const T*> const_iterator;

[snip]

That is a great idea! And I appreciate the other comments too.

Thank you!

--
Christopher Diggins
http://www.cdiggins.com
My question is, how bad is that?


Very bad.
Am I running the risk of undefined behaviour,


Probably depends on what you do with it. One case where it gets you in a
lot of trouble is with threaded code. Modifying state behind the clients
back means that methods that look like they shouldn't require an exclusive
lock actually do require one. For example, it's reasonable to expect that
multiple concurrent readers are OK, but if those readers are secretly
writing, then it's a problem. I suppose you could require that every
element
access of any kind required an exclusive lock, but I'm sure you can see
why
that's unwieldy.
or is the worst case scenario simply const violation?


const violation is already very bad. It makes life very inconvenient when
you
get bugs, because you can no longer trust the word "const" any more.
"const"
is a contract of sorts. When you stop honoring it, it loses its relevance.

Cheers,
--
Donovan Rebbechi
http://pegasus.rutgers.edu/~elflord/

Jul 23 '05 #6
So here is a generalized stride iterator, is it a correct random access
iterator?

template<class Iter_T>
class stride_iter
{
public:
// public typedefs
typedef typename std::iterator_t raits<Iter_T>:: value_type value_type;
typedef typename std::iterator_t raits<Iter_T>:: reference reference;
typedef typename std::iterator_t raits<Iter_T>:: difference_type
difference_type ;
typedef typename std::iterator_t raits<Iter_T>:: pointer pointer;
typedef std::random_acc ess_iterator_ta g iterator_catego ry;
typedef stride_iter self;

// constructors
stride_iter() : m(null), step(0) { };
explicit stride_iter(Ite r_T x, difference_type n) : m(x), step(n) { }

// operators
self& operator++() { m += step; return *this; }
self operator++(int) { self tmp = *this; m += step; return tmp; }
reference operator[](difference_typ e n) { return m[n * step]; }
reference operator*() { return *m; }
friend bool operator==(cons t self& x, const self& y) { return x.m ==
y.m; }
friend bool operator!=(cons t self& x, const self& y) { return x.m !=
y.m; }
friend bool operator<(const self& x, const self& y) { return x.m <
y.m; }
private:
Iter_T m;
difference_type step;
};

Jul 23 '05 #7

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

Similar topics

17
7386
by: Gordon Airport | last post by:
Has anyone suggested introducing a mutable string type (yes, of course) and distinguishing them from standard strings by the quote type - single or double? As far as I know ' and " are currently interchangeable in all circumstances (as long as they're paired) so there's no overloading to muddy the language. Of course there could be some...
18
2577
by: Markus.Elfring | last post by:
The C++ language specification provides the key word "mutable" that is not available in the C99 standard. Will it be imported to reduce any incompatibilities? http://david.tribble.com/text/cdiffs.htm#C99-cpp-keyword http://www.inf.uni-konstanz.de/~kuehl/c++-faq/const-correctness.html#faq-18.13 Regards, Markus
12
6359
by: Kjetil Kristoffer Solberg | last post by:
What is a mutable struct? regards Kjetil Kristoffer Solberg
10
1857
by: Jeff Grills | last post by:
I am an experienced C++ programmer with over 12 years of development, and I think I know C++ quite well. I'm changing jobs at the moment, and I have about a month between leaving my last job and starting my new one. In that time, I have decided to learn C#. I picked up the book, "Programming C# (4th Edition)" recently and have read most of...
90
4351
by: Ben Finney | last post by:
Howdy all, How can a (user-defined) class ensure that its instances are immutable, like an int or a tuple, without inheriting from those types? What caveats should be observed in making immutable instances? -- \ "Love is the triumph of imagination over intelligence." -- |
12
3731
by: Water Cooler v2 | last post by:
Are JavaScript strings mutable? How're they implemented - 1. char arrays 2. linked lists of char arrays 3. another data structure I see that the + operator is overloaded for the string class and hence it is possible to do: txt += "foo bar";
12
3133
by: Vincent RICHOMME | last post by:
Hi, I am currently implementing some basic classes from .NET into modern C++. And I would like to know if someone would know a non mutable string class.
2
4255
by: subramanian100in | last post by:
I am reading David Musser's "STL Tutorial and Reference Guide" Second Edition. In that book, on pages 68-69, definition has been given that "an iterator can be mutable or constant depending on whether the result of operator* is a reference or a constant reference." As per this definition, on page 71 in this book, it is mentioned that for...
24
2491
by: Steven D'Aprano | last post by:
Sometimes it seems that barely a day goes by without some newbie, or not- so-newbie, getting confused by the behaviour of functions with mutable default arguments. No sooner does one thread finally, and painfully, fade away than another one starts up. I suggest that Python should raise warnings.RuntimeWarning (or similar?) when a function...
0
7684
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...
1
7768
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8058
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...
0
6400
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...
1
5579
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5288
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...
0
3729
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3729
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1295
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.