[CLN-list] modular polynomials
bruno at clisp.org
Sat Sep 27 16:48:03 CEST 2008
Alexei Sheplyakov wrote:
> cl_UP is actually a pointer to a coefficient vector. This assignment creates
> the pointer c which points to the same data as a. That's probably not what
> you want. Perhaps you meant
> c = a.ring()->create(degree(a));
> for (std::size_t i = 0; i <= degree(a); ++i)
> c.set_coeff(i, a.coeff(i));
> Actually the semantics is a bit weird. Should we implement operator= which
> "just works"? Or at least document the current behaviour?
Now, this is a design question.
One of the basic principles of CLN is that assignments are fast. Assignments
copy only pointers, and reference counts are used to handle the memory
allocations. Other designs, such as copying entire arrays upon '=', just lead
to slow code.
I see two options.
1) The dilemma that Jens encountered is a classical C++ classes problem, often
seen in C++ classes that represent strings, vectors, etc. For strings,
polynomials, etc. the user expects to have no side effects on earlier copies
of an object. At the same time he also expects to be able to mutate elements
inside the object.
This problem was solved in Java by separating the side-effect-free and the
mutating behaviours into two different classes. See the Java classes for String
 - immutable - and StringBuffer  - mutable, but used only to construct a
String. Because of this, working with strings in Java is both easier and more
efficient than in C++.
You can introduce a new class, say, cl_UP_coefficients or cl_UP_embryo, that
has a set_coeff method and a finalize method that returns a cl_UP. cl_UP will
lose these methods, but have a constructor that takes a cl_UP_coefficients
This is an API change, for the better.
2) The other option is to keep the current design and have set_coeff and
finalize throw an exception when the reference count is > 1. And, of course,
document the behaviour and provide a separate function for "deep copying"
of a polynomial.
My vote goes for 1).
More information about the CLN-list