Re: Unary functor on algorithm using copy constructor
"Dijkstra" <pepitek@gmail.com> wrote in message
news:67314144-bc45-4512-8c5e-d004b15607d0@m3g2000hsc.googlegroups.com...
Hi Jim!
On Jul 8, 7:14 pm, "Jim Langston" <tazmas...@rocketmail.com> wrote:
struct space_comparer : public unary_function<char, bool> {
mutable argument_type __lastChar;
If you need one, and only one __lastChar (a bad choice of names, by the
way)
then you should make it static. I don't think that mutable makes it
static.
static argument_type lastChar_;
I knew many of you would be instantly caught by the double_underscore
issue. :-) I know, I know, it's a bad habit and I promise to flagelate
myself later on.
About the static member attribute, I can't do that since the very use
of static members would kill the multithreaded nature of the program.
The code which used the functor will be automatically non-reentrant,
adding serialization here is killer.
"mutable" attributes can be modified inside "const" functions, i.e.
they don't add to the "const-ness" of the class. Absolutely they don't
become static.
Actually, I come to a solution which I think it's the best suited for
my implementation. It involves using a reference, which is used
instead of the actual member. However, I'm curious about the correct
(and formal) solution, so folks, keep replying... :-)
----------------------
This is what I came up with playing around. If you use some sort of smart
pointer you may get around having to do the CleanUp. I don't know if thsi
is "right" but seems to be doable. Output is:
ctor() called and lastChar is 'X'
copy ctor() called setting lastCharP
copy ctor() called setting lastCharP
[X | c]
[c | p]
[p | p]
copy ctor() called setting lastCharP
copy ctor() called setting lastCharP
[p | c]
[c | p]
[p | p]
copy ctor() called setting lastCharP
copy ctor() called setting lastCharP
[p | c]
[c | p]
[p | p]
#include <functional>
#include <string>
#include <iostream>
#include <algorithm>
struct space_comparer : public std::unary_function<char, bool> {
mutable argument_type* lastCharP;
space_comparer()
{
lastCharP = new argument_type;
*lastCharP = 'X';
std::cout << "ctor() called and lastChar is '" << *lastCharP << "'"
<< std::endl;
}
void CleanUp() const
{
delete lastCharP;
lastCharP = NULL;
}
space_comparer(const space_comparer &__src)
{
std::cout << "copy ctor() called setting lastCharP" << std::endl;
lastCharP = __src.lastCharP;
}
result_type operator ()(const argument_type c) const
{
std::cout << "[" << *lastCharP << " | " << c << "]" << std::endl;
*lastCharP = c;
return ::isspace(c);
}
};
int main()
{
std::string cad1;
std::string cad2;
const space_comparer instance;
cad1 = "cpp";
remove_copy_if(cad1.begin(), cad1.end(), back_inserter(cad2),
instance );
remove_copy_if(cad1.begin(), cad1.end(), back_inserter(cad2),
instance );
remove_copy_if(cad1.begin(), cad1.end(), back_inserter(cad2),
instance );
instance.CleanUp();
return 0;
}