472,354 Members | 1,672 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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 1628
* 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******@videotron.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_iterator {
....
};

typedef general_iterator<T,T*> iterator;
typedef general_iterator<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<typename 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.com> wrote in message
news:sl******************@panix2.panix.com...
On 2005-06-03, christopher diggins <cd******@videotron.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_iterator {
...
};

typedef general_iterator<T,T*> iterator;
typedef general_iterator<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_traits<Iter_T>::value_type value_type;
typedef typename std::iterator_traits<Iter_T>::reference reference;
typedef typename std::iterator_traits<Iter_T>::difference_type
difference_type;
typedef typename std::iterator_traits<Iter_T>::pointer pointer;
typedef std::random_access_iterator_tag iterator_category;
typedef stride_iter self;

// constructors
stride_iter() : m(null), step(0) { };
explicit stride_iter(Iter_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_type n) { return m[n * step]; }
reference operator*() { return *m; }
friend bool operator==(const self& x, const self& y) { return x.m ==
y.m; }
friend bool operator!=(const 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
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...
18
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?...
12
by: Kjetil Kristoffer Solberg | last post by:
What is a mutable struct? regards Kjetil Kristoffer Solberg
10
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...
90
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...
12
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...
12
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
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...
24
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...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. header("Location:".$urlback); Is this the right layout the...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it so the python app could use a http request to get...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...

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.