473,657 Members | 2,515 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 1736
* 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
7391
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 interesting problems with current code that doesn't make a distinction, but it would be dead easy to fix...
18
2582
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
6363
by: Kjetil Kristoffer Solberg | last post by:
What is a mutable struct? regards Kjetil Kristoffer Solberg
10
1865
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 it. I've written about 1,500 lines of C# now, and I've run into the first really ugly thing I...
90
4377
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
3742
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
3142
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
4258
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 'set' and 'multiset', both the iterator and const_iterator types are constant bidirectional types -...
24
2506
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 is defined with a default argument consisting of a list, dict or set. (This is not meant as an...
0
8413
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8740
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8513
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
7352
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
5642
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
4173
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2742
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
1970
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.