Templates and forward declarations

On Sep 25, 12:49 pm, Rune Allnor wrote:
> Hi all.
>
> I have these classes, implemented as templates in header files.
> Right now I have one file per class, where both the declarations
> and implementations of one class are located in each file.
>
> I would like to apply the visitor pattern to some of these classes.
> One of the technicalities behind the visitor pattern is that one
> needs forward declarations of classes, since there are two
> class hierarchies which refer to each other.
>
> In C++ one can refer to a yet undeclared class in one class'
> *declaration*, but one can't refer to undeclared classes in the
> *implementation*. Since the declaration and implementation
> of my classes reside in the same file, my nice system breaks
> down.
>
> Or I need to set up a very entangled network of declarations
> and implementations, which at the end *might* compile *if*
> all the dependencies are carefully orchestrated. Which in turn
> means that all classes need to know about all the other classes,
> which ultimately destroys the nice modular class hierarchy I
> have right now. Or I can lump lots of classes together in one
> header file, which not quite as bad, but hardly modular.
>
> One tempting conclusion from all this is that templates don't
> go well with forward declarations *and* a modular design.
> This seems a bit too 'over the top' to be accepted just like
> that, so am I overlooking something?

Try the following layout:


#if !defined(A_H_INCLUDE_GUARD)
#define A_H_INCLUDE_GUARD

template struct B;

template
struct A
{
void f(B& b);
}

#include "A.ipp"

#endif // !defined(A_H_INCLUDE_GUARD)



include "B.h"

template
void A::f(B& b)
{
// do something with b here
}



#if !defined(B_H_INCLUDE_GUARD)
#define B_H_INCLUDE_GUARD

template struct A;

template
struct B
{
void f(A& a);
}

#include "B.ipp"

#endif // !defined(B_H_INCLUDE_GUARD)



include "A.h"

template
void B::f(A& a)
{
// do something with a here
}


You set up your files the same way as for non-template classes, with
the following difference: The implementation file is not compiled as a
separate translation unit, but is instead #included at the end of the
header file (within the include guard). The suffix .ipp is commonly
used to distinguish the file from .cpp (compiled as a separate
translation unit) and .h/.hpp (an interface file included wherever
needed).

Yechezkel Mett


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Template metafunction returning pointer-to-member

On Sep 24, 5:58 pm, Marsh Ray wrote:
> struct sample
> {
> float member_one;
> };
>
> template struct choose_p2mem { };
>
> template <> struct choose_p2mem
> {
> // Error: a member of type "int sample::*const" cannot have an in-
> class initializer
> //static int sample::* const ptr2mem = &sample::member_one;
>
> static float sample::* const ptr2mem;
>
> };
>
> // Error: "float sample::*const choose_p2mem::ptr2mem" is
> not an entity that can be explicitly specialized
> template <>
> float sample::* const choose_p2mem::ptr2mem =
> &sample::member_one;

It's nothing to do with the ptr-to-member; the same thing would happen
with any type. Try the following:

float sample::* const choose_p2mem::ptr2mem =
&sample::member_one;

(without the "template <>").

The point is that "choose_p2mem" is not a template; it's a
full specialization, which is just a plain class. Note that this
definition will need to go in a cpp file, not a header file, like all
class member definitions.

Yechezkel Mett


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

FFT: Problem with large dataset in memory

On Sep 24, 12:28 pm, Simon Lu wrote:
> I am working in a project dealing with a big many of data. Now I have
> a problem with doing the FFT on a very long time trace, a signal with
> over 300 million sampling points. After testing with my computer, I
> realise that I can store only 2**27 points into memory, which will
> need 2 GB RAM. With an array of 2**28 Double_t points the program
> crash ("segmentation violation").

Clearly, the most natural solution would be to port your current C++
program to a 64-bit execution environment. A 64-bit memory model would
be able to accommodate vastly larger amounts of data in RAM than is
possible under the program's current, 32-bit memory model.

Now porting a C++ program to a 64-bit environment might not turn out
to be as straightforward as one might expect. Issues with C++'s sign
promotion of integer types - especially - can lead to surprising
results. Apple's 64-bit transition programmer's guide: (http://
preview.tinyurl.com/3ns3b5) has some examples.

Greg


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Is self assignment test valid?

"Niels Dekker - no return address" wrote in
news:48da06e1$0$200$e4fe514c@news.xs4all.nl:

> red floyd wrote:
>> if you use a Copy and Swap paradigm, then you don't need to check
>> for self-assignment.
>
> Unless you think that self-assignment should never throw an exception...
>
> My 2 cents,


But if you know are are self-assigning in the first place, why do it at
all? And if you don't know then the assurance that there will be no
exception in that case does not seem so useful either.

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Dynamic initialization of namespace scope objects may be deferred until first use?

On Sep 24, 4:42 pm, Marsh Ray wrote:
> On Sep 24, 10:08 am, JoshuaMaur...@gmail.com wrote:
>
> > In the C++03 standard, 3.6.2/4, it says that globals may have their
> > initialization deferred until the first use of a function or object
> > from that translation unit.
>
> Thank you for raising this. It's timely for me, some code I'm writing
> today could potentially be affected by this. It's non-critical enough
> that I'm probably just going to have to rely on my current compiler's
> eagerness.
>
> > 3- This all rests upon the implicit assumption that no one creates
> > threads before main is called. Is this a fair assumption from real
> > world code? It just seems that what limited guarantees we have
> > concerning the order of construction of globals goes out the window if
> > there's multiple threads before main starts.
>
> As someone who has on occasion had to write such a thing, no, it's not
> a safe assumption in the literal sense. However, there's no way I
> would (intentionally) let the thread's code depend on the construction
> of your globals.

That seems like a risky proposition. Singletons can be used to
implement interfaces, and other interfaces can use the singleton's
interface, and other interfaces can use those interfaces, etc. It has
a ripple effect up through the interfaces which ever directly or
indirectly use a singleton.

Using an eager-initialized no-locking singleton is no longer an
implementation detail. You would need to spell out in the contract of
the interface: "This interface uses a static local object which is
eager initialized by a namespace member. If the first call to this
interface is before main(), then the first call is not thread-safe."

I suppose you could use the thread local storage singleton pattern
which has thread-safe initialization as well, and avoid the
complication in the interface's contract.


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Dynamic initialization of namespace scope objects may be deferred until first use?

On Sep 24, 4:37 pm, Mathias Gaunard wrote:
> On 24 sep, 17:08, JoshuaMaur...@gmail.com wrote:
[...]
> > T& getInstance()
> > { static T * t = new T;
> > return *t;
> > }
>
> That's a static variable within a function.
> How is that a global variable?
>
> Define clearly what you're talking about first.

I'm sorry, I should have used "namespace member" instead of global.
The namespace member is now highlighted in the following copy and
paste by a comment.

class T { /*...*/ };
T& getInstance()
{ static T * t = new T;
return *t;
}
namespace
{ struct ForceInstantiation
{ ForceInstantiation() { getInstance(); }
} force; //!!force is a namespace member!!
}

If the namespace member is guaranteed to be constructed before main is
called, and we can otherwise guarantee that no threads will be created
before main is called (and that all namespace member initialization
finishes before a dll_load returns), then this is a thread-safe no-
locking eager-initialized singleton. (In the second example, there is
a namespace member which forces the construction of the mutex before
main is called (or at least attempts to), thus guaranteeing thread-
safe concurrent access on the first call to the singleton.)

However, the initialization of the namespace member may be delayed
until the first reference to the translation unit, which effectively
puts me at the mercy of my compiler writer to guarantee thread safety.
I suppose I was always at the mercy of the compiler writer. The
compiler writer had to say "We support pthreads", but I don't know
offhand whether the pthreads standard actually mentions this deferring
of dynamic initialization of namespace members.

If the initialization of namespace members is allowed, the above
idiomatic approaches are not guaranteed to work.

I suppose I could just use pthread_once (or whatever it is), but that
would mean large amounts of current code is broken, as large amounts
of code rely upon the above idioms to be correct.

> AFAIK, static variables within functions are always lazily evaluated
> and are perfectly thread-safe in C++0x. They're the recommended way to
> write singletons (meyers singleton), unless destruction order matters.

I specifically said for C++03. We're stuck with working with C++03 for
probably at least the next 5 years. We're stuck with C++03 because we
have to wait until all the compiler writers on all the platforms my
company supports decide to actually implement the new standard, which
might be several (more likely many) years after it's released.


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?

Andrei Alexandrescu wrote:
>
> There's one thing with this approach, that it requires the
> zero-initialized state to be a sort of bad state.
>

This isn't a big limitation and, in the rare case it might turn out to
be one, there is an easy workaround (see below). Yes is_zombie() will
return true for an object that is all zeroes but why is it bad? Your
code may contain:

if (!is_zombie(p))
delete p;

so for an empty struct Point { unsigned x, y; } you will not call the
destructor but so what? This class doesn't need the destructor at all
to begin with. The only time you need a destructor is if you have a
non-null pointer or, possibly, some kind of non-zero integral "handle"
as a member. And this will be nicely handled but my scheme.

> Consider:
>
> struct Point { unsigned x, y; const char* color; }

Good example. If the color is NULL then you don't need to call the
dtor. If it isn't then the object is not a zombie.

Of course you probably can devise clever examples where:
a) a resource is owned via a zero handle or
b) you really want to distinguish between zombie and all-zero state
for some reason I cannot yet imagine ;-) (I'd appreciate any such
example)

In this case the easy workaround is to add

bool is_initialized;

member to such class set it to true in ctor and false in dtor.

The reason I know this issue isn't such a big deal is because the
approach I described is simply an automatic version of a manual one
currently used in Java, C# and C++/CLI. There too theoretically it is
impossible to distinguish between an zero object and the one just
before the constructor/zombie state but it doesn't seem to cause any
significant problems.

--
Eugene

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?

David Abrahams wrote:
> on Wed Sep 24 2008, Andrei Alexandrescu wrote:
>
>> David Abrahams wrote:
>>> on Tue Sep 23 2008, Andrei Alexandrescu
>> wrote:
>>>> That's pretty much why I dislike the term zombie for a terminated
>>>> object. To me that object should be eminently usable, just that it is in
>>>> an empty state where it consumes no resources beyond its own bits.
>>>>
>>>> In that view of the world, objects remain infinitely-lived as they've
>>>> always been in a GC system. On top of that, destructors just make sure
>>>> that additional resources that objects occasionally acquire are released
>>>> at specific boundaries. To be honest, the more I think about that model,
>>>> the more I like it. :o)
>>> So IIUC, in this model:
>>>
>>> * you still need to remember to tear everything down before you leak it
>> Not if you use scoped ownership as is often the case in C++.
>
> At the top level, if it's not on the stack, you're not leaking anything
> in that case. Otherwise, you need something analogous to p->~T() at the
> top level.
>
>>> * torn-down objects are just as good as any others
>> Yah.
>>
>>> * you don't get any help finding places where you use torn-down
>>> objects, because it's totally legal to do so
>> Yah. You can build support inside the objects themselves when there's
>> a need for it.
>
> Hmmm.... so most torn-down objects are "in a good state," but some are
> not.
>
>>> * GC is buying you some type safety
>> Yah.
>>
>>> Have I got that right?
>> Yah.
>>
>>> Do you place objects on the stack, or is it a world of GC'd pointers?
>> Great question. Objects can live on the stack. If the seatbelt is on,
>> escaping of addresses of locals is statically verboten.
>
> Then this is not C++. I might've guessed, but I wish that had been
> clear from the start.

I think there would be a lot of merit in the notion of a safe C++ in
which certain operations are statically rejected. We've gone some of
that way already, with three-argument std::copy raising an increasing
amount of eybrows and with compiler warnings at strcpy, sprintf et al.

Aout the larger discussion, upon more thinking, I was really
hard-pressed to come up with valid designs resuscitating zombie objects.
I think it's better to say that once a destructor has run, it should
mark the resource as just gone. The object remains in there for type
safety, so behavior is reproducible, but should refuse to reallocate
resources because it can't release them. Not very attractive...


Andrei


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?


on Wed Sep 24 2008, Andrei Alexandrescu wrote:

> Either an operation does the work on
> the side and swap()s it with the original object, or first saves a
> copy of the object, operates on the original object, and in case that
> fails swaps the old content back into the object.

Or neither. Take a look at vector::push_back.

The standard library gives the strong guarantee in precisely those cases
where it doesn't have to make a copy/swap sacrifice.

> Surprise, surprise, the requirement that rollback be nothrow is the
> moral equivalent of the commit being nothrow.

I don't understand the point you're trying to make here, but I think
your premise above isn't quite right, so you might want to reconsider in
that light.

--
Dave Abrahams
BoostPro Computing
http://www.boostpro.com

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Templates and forward declarations

Hi all.

I have these classes, implemented as templates in header files.
Right now I have one file per class, where both the declarations
and implementations of one class are located in each file.

I would like to apply the visitor pattern to some of these classes.
One of the technicalities behind the visitor pattern is that one
needs forward declarations of classes, since there are two
class hierarchies which refer to each other.

In C++ one can refer to a yet undeclared class in one class'
*declaration*, but one can't refer to undeclared classes in the
*implementation*. Since the declaration and implementation
of my classes reside in the same file, my nice system breaks
down.

Or I need to set up a very entangled network of declarations
and implementations, which at the end *might* compile *if*
all the dependencies are carefully orchestrated. Which in turn
means that all classes need to know about all the other classes,
which ultimately destroys the nice modular class hierarchy I
have right now. Or I can lump lots of classes together in one
header file, which not quite as bad, but hardly modular.

One tempting conclusion from all this is that templates don't
go well with forward declarations *and* a modular design.
This seems a bit too 'over the top' to be accepted just like
that, so am I overlooking something?

Rune

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

How to test if value_type is complex<double> or just double?

On Sep 24, 6:36 pm, jeremit0 wrote:
> Is there anyway to check what kind of type is
> contained in the vector (i.e. x::value_type == double)? Even better
> would be some cool template that would take care of this at compile
> time.

Sure, http://www.boost.org/doc/libs/release/libs/utility/enable_if.html
for example.

But can't you just define an additional specialization?

template <>
void func(
std::vector > & x,
std::vector > y ) // Pass 'y' by ref here?
{
// "split it into the real and imaginary parts"
std::vector x_re, x_im;
std::vector y_re, y_im;
...

// "call the second version"
func(x_re, y_re);
func(x_im, y_im);
}

- Marsh

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?

Erik Wikström wrote:
> On 2008-09-24 03:15, Andrei Alexandrescu wrote:
>
>> Since we already expend effort in ensuring there's no dangling pointers,
>> there's no extra effort needed.
>
> I must ask, since your main motivation for this scheme seems to be to
> prevent dangling pointers, does the C++ programming community as a whole
> have great problems with dangling pointers? I know that I myself never
> had much problems with them, and where I'm currently working I think
> most of our pointer-related problems are memory-leaks or uninitialised/
> NULL pointers. And we are writing in C, where we do not have the benefit
> from constructors/destructors.

If you have too many memory leaks, you have too few dangling pointers.

Andrei :o)


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

compile-time constraints on a macro parameter

In article , Seungbeom Kim
wrote:

> blargg wrote:
> > In article
> > ,
> > JoshuaMaurice@gmail.com wrote:
> >
> >> On Sep 20, 6:51 pm, Jeff Schwab wrote:
> >>> Marsh Ray wrote:
[...]
> >> #define macro(x) if (true) {/*something*/} else (void)(0)
[...]
> > That's misleading, as it now acts like a never-evaluated expression,
> > allowing comma:
> >
> > macro(), never_called();
>
> I think it was something like this:
>
> #define macro(x) if (false) { } else (x)

How is that any better than

#define macro(x) (x)

? I think the point was that {/*something*/} is a compound block, not an
expression, so no semicolon is required after it. Thus, to require one,
the macro must end in something requiring a semicolon.

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?

James Hopkin wrote:
> On Sep 23, 1:29 am, Andrei Alexandrescu
> wrote:
>> Mathias Gaunard wrote:
>>> All default constructors of containers are not required to be nothrow.
>>> Electronic Arts has asked the standard to change that, however,
>>> showing their own EASTL as an improvement upon the STL.
>> I'm of the same opinion as them.
>>
>> Andrei
>>
>
> Me too, but I don't think it implies much about whether throwing
> default constructors *in general* are problematic.

I agree. So let me restart. Do you agree that in a GC system, there
should be _some_ constructor that doesn't throw (that being the
constructor called when the object enters the destroyed state)? If we do
agree on that, what remains is to define that constructor.

> I think extrapolating too much from containers can be helpful but
> potentially misleading. Over-generalising in the other direction:
> containers are more malleable and have simpler invariants than a lot
> of types.

I agree with that too.


Andrei


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?

On 2008-09-24 17:06, Eugene Gershnik wrote:
> Andrei Alexandrescu wrote:
>> This is a very fertile subject. As an aside, I'm a bit surprised that
>> most people spend energy solely on rehashing the known problems with GC
>> + destructors. Yes, it is understood there are problems. The more
>> interesting and challenging task is to define a system that does work.
>> Clearly it can't work exactly like today because the tradeoff space is
>> very different, but let's look for something that does work and presents
>> another, hopefully better but still different, tradeoff proposition.
>
> Well here are 3 things that can be done in order to make destructors
> work well with GC
>
> 1) Make the language zero initialize[1] object bits prior to running
> any constructor. This is your zombie state (as opposed to the one
> after default constructor)
> 2) Make the language wipe the object to the same zero-initialized
> state after desturctor finishes. This frees programmer to write
> destructors as he always had done and ensures that a single well
> defined zombie state is reached automatically.
> 3) Make the language supply a function is_zombie() that returns true
> if the object is in that same zero-initialized state. This, again,
> prevents the programmer from making a mistake in writing one manually.
> In general the object itself doesn't need to call this function, only
> its users are if they have reason to believe that an object might be a
> zombie.

How do you distinguish a zombie from a valid object which happens to be
all zeroes? Imagine a simple class such as

struct Complex {
double re, im;
};

where all bits of the object being 0 is a valid state. I can see no safe
way of marking an object as zombie without using dedicated memory for it.

--
Erik Wikström


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?

Dave Harris wrote:
> SeeWebsiteForEmail@erdani.org (Andrei Alexandrescu) wrote (abridged):
>> Consider a File type that provides the usual operations.
>
> Certainly there are situations where the approach is painless and then
> it's the natural thing to do. Vector is one example, and File is another.
> File in particular because you expect to have to tell it the name of the
> file you want to use, so it makes sense to have an explicit "open" step
> before using the other operations. I agree that where it is easy it is
> often good idea to postpone acquiring resources until they are actually
> needed.
>
> The tricky situations are where the object doesn't need any arguments to
> be usable, because then it feels unnatural to have an explicit "open"
> step, and without that we get a can of worms with resurrection,
> unexpected throws, efficiency hits etc. If we want a general rule, then
> we have to think about the difficult cases.

I agree. But then if both painful/painless situations are useful, then
it may make sense to classify them in distinct bins. Right now they're
in the same bin.

>> When File's destructor gets called, the underlying file handle
>> is closed, thus freeing the resource. [...]
>>
>> Can the file be reopened post destruction? [...] Yes [...]
>
> When you say "destructor", do you mean "dispose"?

Yah.

> In standard C++, the destructor changes the type of the object, from
> derived class to base class and then to raw memory. The vtable pointer
> gets reset.
>
> struct BaseFile {
> virtual bool open( const char *name );
> };
> struct File {
> virtual bool open( const char *name );
> };
>
> It sounds like after "File's destructor gets called", you still expect a
> call to open() to invoke File::open() rather than BaseFile::open(). If so,
> then I'd rather not use the terminology of destruction, destructors etc.
> The word "dispose" better reflects the meaning.

Good point. The compiler could do some footwork in calling that
nonthrowing default constructor for File right after destruction.

> I don't think the keyword "delete" should be changed to mean dispose in a
> GC environment. That's too scary a change for me.

I understand. I do think that would be a sensible decision for D, it
being a new language built with GC from the get-go.

>> This is a very fertile subject. As an aside, I'm a bit surprised
>> that most people spend energy solely on rehashing the known
>> problems with GC + destructors. Yes, it is understood there are
>> problems. The more interesting and challenging task is to define
>> a system that does work.
>
> We should be no worse off if instead of the object being destroyed, it is
> left in a zombie state with well-defined behaviour at the language level.
> This is an opportunity, and I agree it warrants some thought as to how
> best to exploit it.
>
> However, although resurrection can make sense, in most cases if you
> dispose an object it will mean you are finished with it, and using it
> after would be a bug. So I see GC/disposal as providing opportunities to
> better detect bugs, and whether to throw an exception or assert depends
> on how one thinks bugs should be dealt with: whether one believes in
> defensive programming or design by contract.

I think we all need some mindset adjustment when trying to reconcile GC
with deterministic resource management. I'd be the first to admit that
my mindset is not entirely adjusted. For example zombie states and
resurrection are both regarded with contempt, but I see them more as
"unowned" and "owned" states. It is easy to provide a flag and functions
like "own", "disown", and "is_owned" for an object that needs them. In
that model, the user of a resource could ask whether that resource has
an owner, and releasing it explicitly if it has no owner.

> (That's also my conclusion about finalisers, although for different
> reasons. I don't believe there is much useful that can be done with a
> finaliser except to detect the mistake of failing to dispose the object.)

Yah finalisers are pretty botched.

> So to me the default constructed state is the opposite of the disposed
> state. One is the start of the object's lifetime, and the other is
> effectively the end. And to tie these together, and say that the default
> constructed state should be the same as the disposed state, is a bit
> unnatural. Much of what you write seems to be tantamount to saying
> defensive programming wins.

I don't particularly like defensive programming, but I also wanted to
make a simple proposition that does not add a specific state.

>> But then again: in discussing the disadvantages of
>> an approach, don't forget the advantages.
>
> It sounds like the main advantage you seek is for default construction
> not to throw. But in C++, construction is exactly when I do expect the
> object to throw, because of RAII. (And because they are often created on
> the heap, and operator new() can throw.) I am more surprised if
> subsequent, apparently innocuous methods throw (because they are secretly
> acquiring resources that should have been got in the constructor).

I think things can be worked out even if the default constructor does
throw. (It would require destructors to be able to throw, which is
possible and IMHO needed by C++.) But allow me this conjecture:

1. If a default constructor may throw, it can be presumed that it failed
to acquire proper state.

2. Because of that it can be presume that whatever was needed was in
scarce supply.

3. Then that means that supply should be refunded pronto, otherwise
other objects will have even less of it.

4. Then the post-destructed state should not default-construct the
object because that works straight against the notion of pronto refunding.

So we go back to the idea that post-destroyed state is distinct from all
other states yet valid, which IMHO brings more problems than it solves.


Andrei

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?

On 2008-09-24 03:15, Andrei Alexandrescu wrote:

> Since we already expend effort in ensuring there's no dangling pointers,
> there's no extra effort needed.

I must ask, since your main motivation for this scheme seems to be to
prevent dangling pointers, does the C++ programming community as a whole
have great problems with dangling pointers? I know that I myself never
had much problems with them, and where I'm currently working I think
most of our pointer-related problems are memory-leaks or uninitialised/
NULL pointers. And we are writing in C, where we do not have the benefit
from constructors/destructors.

--
Erik Wikström


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Dynamic initialization of namespace scope objects may be deferred until first use?

On Sep 24, 10:08 am, JoshuaMaur...@gmail.com wrote:
> In the C++03 standard, 3.6.2/4, it says that globals may have their
> initialization deferred until the first use of a function or object
> from that translation unit.

Thank you for raising this. It's timely for me, some code I'm writing
today could potentially be affected by this. It's non-critical enough
that I'm probably just going to have to rely on my current compiler's
eagerness.

> 3- This all rests upon the implicit assumption that no one creates
> threads before main is called. Is this a fair assumption from real
> world code? It just seems that what limited guarantees we have
> concerning the order of construction of globals goes out the window if
> there's multiple threads before main starts.

As someone who has on occasion had to write such a thing, no, it's not
a safe assumption in the literal sense. However, there's no way I
would (intentionally) let the thread's code depend on the construction
of your globals.

- Marsh

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

FFT: Problem with large dataset in memory

On Sep 24, 8:28 pm, Simon Lu wrote:
> Hi,
>
> I am working in a project dealing with a big many of data. Now I have
> a problem with doing the FFT on a very long time trace, a signal with
> over 300 million sampling points. After testing with my computer, I
> realise that I can store only 2**27 points into memory, which will
> need 2 GB RAM. With an array of 2**28 Double_t points the program
> crash ("segmentation violation"). I tried the Root cern framework, gsl
> and fftw3 library. They all need to load the data into memory. So the
> question is: Are there some mechanisms or algorithms to manage the
> array on a TTree or somewhere else on the hard disk? And then load the
> the data step by step into cache? Something likes a FileArray. Or you
> get a better idea?
> This is really urgent. I am very grateful if I can hear something from
> you!
> THX!

Write the whole array into a file (binary format)
Then link the file to the process using mmap()
then you can use some sort of indexing to locate the data in the file.


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

FFT: Problem with large dataset in memory

Simon Lu schrieb:
> I am working in a project dealing with a big many of data. Now I have
> a problem with doing the FFT on a very long time trace, a signal with
> over 300 million sampling points. After testing with my computer, I
> realise that I can store only 2**27 points into memory, which will
> need 2 GB RAM. With an array of 2**28 Double_t points the program
> crash ("segmentation violation"). I tried the Root cern framework, gsl
> and fftw3 library. They all need to load the data into memory. So the
> question is: Are there some mechanisms or algorithms to manage the
> array on a TTree or somewhere else on the hard disk? And then load the
> the data step by step into cache? Something likes a FileArray. Or you
> get a better idea?

Although this is not directly C++-related: You may want to check the
Cooley-Tukey algorithm which lets you calculate an FFT by applying it to
(for instance) the even- and odd-indexed numbers separately and then
combining the result - see for example
.
This may be applied in a recursive manner, so you should be able to
reduce the block size until everything fits in memory. This algorithm
and its variants also allow to reach a O(N log N) runtime as opposed to
O(N^2) for a naive implementation, so it is probably already used
internally by the FFT libraries you mentioned.

HTH
Falk

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

C++ BitVector compression and encryption

allswellthatendswell wrote:
> We are developing a C++ bitvector class and we were wondering if
> anyone could provide us with ideas for compressing bit vectors in c++?
> Would Huffman encoding be able to handle bitvectors of 1000 bits?
> Also, we are interested in how to encrypt a compressed bit
> vector. Thank you.

I feel this question fits better in a different group, related to
compression or encryption (that is, coding or information theory?).
The details of gzip, for example, is off topic here.

That being said, if you have an issue implementing whatever algorithm
in C++, the folks here can certainly help you.

--
Seungbeom Kim

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?


on Wed Sep 24 2008, Andrei Alexandrescu wrote:

> David Abrahams wrote:
>> on Tue Sep 23 2008, Andrei Alexandrescu
> wrote:
>>
>>> That's pretty much why I dislike the term zombie for a terminated
>>> object. To me that object should be eminently usable, just that it is in
>>> an empty state where it consumes no resources beyond its own bits.
>>>
>>> In that view of the world, objects remain infinitely-lived as they've
>>> always been in a GC system. On top of that, destructors just make sure
>>> that additional resources that objects occasionally acquire are released
>>> at specific boundaries. To be honest, the more I think about that model,
>>> the more I like it. :o)
>>
>> So IIUC, in this model:
>>
>> * you still need to remember to tear everything down before you leak it
>
> Not if you use scoped ownership as is often the case in C++.

At the top level, if it's not on the stack, you're not leaking anything
in that case. Otherwise, you need something analogous to p->~T() at the
top level.

>> * torn-down objects are just as good as any others
>
> Yah.
>
>> * you don't get any help finding places where you use torn-down
>> objects, because it's totally legal to do so
>
> Yah. You can build support inside the objects themselves when there's
> a need for it.

Hmmm.... so most torn-down objects are "in a good state," but some are
not.

>> * GC is buying you some type safety
>
> Yah.
>
>> Have I got that right?
>
> Yah.
>
>> Do you place objects on the stack, or is it a world of GC'd pointers?
>
> Great question. Objects can live on the stack. If the seatbelt is on,
> escaping of addresses of locals is statically verboten.

Then this is not C++. I might've guessed, but I wish that had been
clear from the start.

> But escaping of addresses of objects indirectly owned by stack locals
> is allowed.

--
Dave Abrahams
BoostPro Computing
http://www.boostpro.com

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

FFT: Problem with large dataset in memory

On 2008-09-24 21:28, Simon Lu wrote:
> Hi,
>
> I am working in a project dealing with a big many of data. Now I have
> a problem with doing the FFT on a very long time trace, a signal with
> over 300 million sampling points. After testing with my computer, I
> realise that I can store only 2**27 points into memory, which will
> need 2 GB RAM. With an array of 2**28 Double_t points the program
> crash ("segmentation violation"). I tried the Root cern framework, gsl
> and fftw3 library. They all need to load the data into memory. So the
> question is: Are there some mechanisms or algorithms to manage the
> array on a TTree or somewhere else on the hard disk? And then load the
> the data step by step into cache? Something likes a FileArray. Or you
> get a better idea?
> This is really urgent. I am very grateful if I can hear something from

There are many ways to do what you want, and the best way depends on
your needs. If you need to operate on the whole dataset at once you have
somewhat of a problem, if you are able to work with just a few data-
points at a time you should be able to "stream" the data through your
algorithm and can probably get away with a fairly small memory footprint.

None of this is however directly topical in this group, is is on a to
high level and have no C++ specific parts, try asking in a general
programming group, such as comp.programming, instead.

If you are running on Windows you might also be able to increase the
virtual memory available for your application to 3GB, for more info:
http://www.microsoft.com/whdc/system/platform/server/PAE/PAEmem.mspx

--
Erik Wikström


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

FFT: Problem with large dataset in memory

On 24 Sep, 21:28, Simon Lu wrote:
> Hi,
>
> I am working in a project dealing with a big many of data. Now I have
> a problem with doing the FFT on a very long time trace, a signal with
> over 300 million sampling points. After testing with my computer, I
> realise that I can store only 2**27 points into memory, which will
> need 2 GB RAM. With an array of 2**28 Double_t points the program
> crash ("segmentation violation"). I tried the Root cern framework, gsl
> and fftw3 library. They all need to load the data into memory. So the
> question is: Are there some mechanisms or algorithms to manage the
> array on a TTree or somewhere else on the hard disk? And then load the
> the data step by step into cache? Something likes a FileArray. Or you
> get a better idea?
> This is really urgent. I am very grateful if I can hear something from
> you!
> THX!

The important question here is why you want to compute the FFT.
There are two main uses of the FFT:

1) Spectrum analysis
2) 'Fast' convolution

The numbers you state make no sense in the context of spectrum
analysis, so I assume you do this to do some filtering or
convolution.

If this is the case, be aware that the FFT is faster than
filtering or convolution in time domain only with 'short'
data sequences. The FFT is a O(NlogN) algorithm, while
direct convolution is O(N*M) where M is the number of
filter coefficients.

This means that if N is large enough and M is small enough,
M < log N and the program will actually run faster and the
data logistics become easier if you use the straight-forward
direct convolution algorithm.

Of course, inserting the numbers and deducing the limit
where the FFT is slower is not at all trivial, so you
might have to resort to trial-and-error. However, the
numbers you state are of such magnitude that you might
very well find that the direct implementation is faster.

Now, if you really need the FFT anyway, you can exploit
the fact that each level of the FFT is a composite of
lower-order FFTs. It is conceivable that you might
be able to compute 2^27-pt FFTs in RAM, store the
results to file and do whatever tricks are needed to
combine these intermediate data into the desired result.

The composite FFTs have been discussed numerous times
on comp.dsp.

Rune

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

FFT: Problem with large dataset in memory


> This is really urgent. I am very grateful if I can hear something from
> you!
> THX!
>
This is off-topic and unrelated to C++.

You can do the FFT in parts in divide and conquer. Do the even
elements and the odd elements individually. If that's too much,
divide each of those FFTs into odd and even, then recombine.

FFT is a classic divide and conquer algorithm. I think the book
"Numerical Recipes" may be useful here.

Joe

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

How to test if value_type is complex<double> or just double?

I have a templated function that looks like:

template
void func(X& x, Y& y){ … }

I have specialized the function as:
template<>
void func(std::vector& x, std::vector y){ … }

In the first version, I want to convert x and y to std::vector
(I assume they are some sort of container) and then call the second
version to do the real work. If–in the first version–x or y is a
std::vector > then I want to split it into the real
and imaginary parts and then call the second version.

Now for the question. Is there anyway to check what kind of type is
contained in the vector (i.e. x::value_type == double)? Even better
would be some cool template that would take care of this at compile
time.

Thanks,
Jeremy


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

SFINAE?

On 24 sep, 15:47, Andrey Tarasevich
wrote:
> courp...@gmail.com wrote:
>
> >> Please, consider the following code sample
>
> >> template void foo(const T&, char(*)[sizeof(T) - 1] = 0);
>
> >> int foo(...);
>
> >> int main()
> >> {
> >> char c;
> >> return foo(c);
> >> }
>
> >> When I try to compile it with Comeau online, it compiles fine, meaning
> >> that the call gets resolved to 'foo(...)'. I assume that it's SFINAE
> >> that kicks in in this case, preventing the template specialization from
> >> being considered as a candidate function (since the array size in the
> >> second parameter evaluates to zero).
>
> >> However, if I change the template declaration to
>
> >> template int foo(const T&, char[sizeof(T) - 1] = 0);
>
> >> Comeau complains with
>
> >> error: the size of an array must be greater than zero
> >> int foo(const T&, char[sizeof(T) - 1] = 0);
> >> ^
> >> detected during instantiation of "foo" based on template
> >> argument
>
> >> Assuming that Comeau is right to complain, why doesn't SFINAE work in
> >> this case as well?
>
> > Strictly speaking, both cases should not lead to SFINAE, since the
> > second function parameter (of both cases) can't be qualified as a
> > nondeduced context : that means the substitution of the template
> > parameter T for the second function parameter doesn't fall in the
> > concerned paragraph [14.8.2/4]. There is consequently no deduction
> > failure and then no SFINAE.
>
> OK, but SFINAE aside, is there a fundamental difference between my two
> examples, which can explain the fact that the former one is accepted by
> the compiler, while the latter one is rejected? Or is it just a quirk or
> Comeau compiler?

Well, without caring about SFINAE and nondeduced contexts, your first
function declaration attemps to create an array of zero element, which
is listed as a substitution failure in [14.8.2/2], whereas your second
function creates a pointer to an array of zero element, which (maybe
arguably) isn't listed in [14.8.2/2].

Alexandre Courpron.


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Dynamic initialization of namespace scope objects may be deferred until first use?

On 24 sep, 17:08, JoshuaMaur...@gmail.com wrote:
> In the C++03 standard, 3.6.2/4, it says that globals may have their
> initialization deferred until the first use of a function or object
> from that translation unit.
>
> [...]
>
> T& getInstance()
> { static T * t = new T;
> return *t;
> }

That's a static variable within a function.
How is that a global variable?

Define clearly what you're talking about first.

AFAIK, static variables within functions are always lazily evaluated
and are perfectly thread-safe in C++0x. They're the recommended way to
write singletons (meyers singleton), unless destruction order matters.


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

FFT: Problem with large dataset in memory

Moin!

Simon Lu writes:

> Hi,
>
> I am working in a project dealing with a big many of data. Now I have
> a problem with doing the FFT on a very long time trace, a signal with
> over 300 million sampling points. After testing with my computer, I
> realise that I can store only 2**27 points into memory, which will
> need 2 GB RAM. With an array of 2**28 Double_t points the program
> crash ("segmentation violation").

[...]

> And then load the the data step by step into cache? Something likes
> a FileArray. Or you get a better idea? This is really urgent. I am
> very grateful if I can hear something from you! THX!

man mmap

hth,

Christoph

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?


on Sat Sep 20 2008, brangdon-AT-cix.co.uk (Dave Harris) wrote:

> For me one of the main ways a default constructor is special is that it
> is used for arrays. So the question is whether code like:
> Foo array[100];
>
> should create 100 zombie Foos, or 100 usable ones. The people who don't
> expect code to throw would presumably want zombies, but I can imagine
> situations where having to follow this with a loop:
>
> Foo array[100];
> for (int i = 0; i < 100; ++i)
> array[i].initialise();
>
> would be inelegant. And of course the opposite, eg where an array of N
> items is allocated in advance but only the first M items are in use and
> need to consume resources.
>
> I don't think we can have absolute rules here, only guidelines.

When you change the deterministic destruction contract, you'd darn well
better have a well-considered programming model to account for the
changes. I don't think "guidelines" are sufficient.

--
Dave Abrahams
BoostPro Computing
http://www.boostpro.com

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?

Nevin :-] Liber wrote:
> In article ,
> Andrei Alexandrescu wrote:
>
>> But the File
>> object does not disappear! It only zeroes its internal file handle, such
>> that whenever an iterator tries to use it the closed state can be
> detected.
>
> In this system, whose responsibility is it to put in such a state?
> Should the destructor do it, or would the compiler insert code after the
> destructor to "placement new" a default constructed object in its place?

Good question. I think the destructor should take care of that. The
problem is that sometimes overwriting is not necessary and therefore
becomes wasted time.

> The reason I ask is if I have a simple object, such as
>
> struct SomeFunctor
> {
> SomeFunctor(State* state = 0) : state(State) {}
> State* state;
>
> void operator()(Var& var) { /* Do something */ }
> };
>
> it should not require the author to write a destructor, force the author
> to use some kind of smart pointer to NULL it, etc., just to make the GC
> system happy. Simple things need to remain simple.

Agreed. Notice that in this cases there's no resource ownership to start
with, so perhaps there is no need to do the automatic overwriting
thingy. That should be done only if the class defines the destructor. I
guess :o).


Andrei

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?

David Abrahams wrote:
> on Tue Sep 23 2008, Andrei Alexandrescu
wrote:
>
>> That's pretty much why I dislike the term zombie for a terminated
>> object. To me that object should be eminently usable, just that it is in
>> an empty state where it consumes no resources beyond its own bits.
>>
>> In that view of the world, objects remain infinitely-lived as they've
>> always been in a GC system. On top of that, destructors just make sure
>> that additional resources that objects occasionally acquire are released
>> at specific boundaries. To be honest, the more I think about that model,
>> the more I like it. :o)
>
> So IIUC, in this model:
>
> * you still need to remember to tear everything down before you leak it

Not if you use scoped ownership as is often the case in C++.

> * torn-down objects are just as good as any others

Yah.

> * you don't get any help finding places where you use torn-down
> objects, because it's totally legal to do so

Yah. You can build support inside the objects themselves when there's a
need for it.

> * GC is buying you some type safety

Yah.

> Have I got that right?

Yah.

> Do you place objects on the stack, or is it a world of GC'd pointers?

Great question. Objects can live on the stack. If the seatbelt is on,
escaping of addresses of locals is statically verboten. But escaping of
addresses of objects indirectly owned by stack locals is allowed.


Andrei

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

C++ BitVector compression and encryption

On Sep 24, 1:58 pm, allswellthatendswell
wrote:
> We are developing a C++ bitvector class and we were wondering if
> anyone could provide us with ideas for compressing bit vectors in c++?
> Would Huffman encoding be able to handle bitvectors of 1000 bits?
> Also, we are interested in how to encrypt a compressed bit
> vector. Thank you.
>

Suppose the 1000 bits consist of 500 randomly distributed 1's and
500 randomly distributed 0's. Then, it is virtually impossible to
compress the 1000 bits any further. Of course, this is a rare case but
it is a possibility. That is what makes the choice between http://zlib.net/
, http://www.oberhumer.com/opensource/lzo/
, and http://www.bzip.org/ so difficult.
We were wondering whether the choice of a compression method and
an encryption are related. In other words, are some compression
methods easier to attack crptographically? Thank you.


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

FFT: Problem with large dataset in memory

Hi,

I am working in a project dealing with a big many of data. Now I have
a problem with doing the FFT on a very long time trace, a signal with
over 300 million sampling points. After testing with my computer, I
realise that I can store only 2**27 points into memory, which will
need 2 GB RAM. With an array of 2**28 Double_t points the program
crash ("segmentation violation"). I tried the Root cern framework, gsl
and fftw3 library. They all need to load the data into memory. So the
question is: Are there some mechanisms or algorithms to manage the
array on a TTree or somewhere else on the hard disk? And then load the
the data step by step into cache? Something likes a FileArray. Or you
get a better idea?
This is really urgent. I am very grateful if I can hear something from
you!
THX!

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?

Eugene Gershnik wrote:
> Andrei Alexandrescu wrote:
>> This is a very fertile subject. As an aside, I'm a bit surprised that
>> most people spend energy solely on rehashing the known problems with GC
>> + destructors. Yes, it is understood there are problems. The more
>> interesting and challenging task is to define a system that does work.
>> Clearly it can't work exactly like today because the tradeoff space is
>> very different, but let's look for something that does work and presents
>> another, hopefully better but still different, tradeoff proposition.
>
> Well here are 3 things that can be done in order to make destructors
> work well with GC
>
> 1) Make the language zero initialize[1] object bits prior to running
> any constructor. This is your zombie state (as opposed to the one
> after default constructor)
> 2) Make the language wipe the object to the same zero-initialized
> state after desturctor finishes. This frees programmer to write
> destructors as he always had done and ensures that a single well
> defined zombie state is reached automatically.
> 3) Make the language supply a function is_zombie() that returns true
> if the object is in that same zero-initialized state. This, again,
> prevents the programmer from making a mistake in writing one manually.
> In general the object itself doesn't need to call this function, only
> its users are if they have reason to believe that an object might be a
> zombie.

There's one thing with this approach, that it requires the
zero-initialized state to be a sort of bad state. Consider:

struct Point { unsigned x, y; const char* color; }

In some design a zero-initialized point could mean a black point at the
origin. The problem is that that's also a zombie point, which comes off
as a surprise.

Other than that, this is a pretty good scheme. But I see the above a
major issue.


Andrei

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Overloading on return value (with a trick)

> { avoid using non-ASCII characters like '<' or '.' in your messages.
> your posting software can most likely be set up not to allow those.
> thanks! -mod }

o_O
It seems that the moderation software already took care of the issue. ;)

jaybus56 wrote:
[overloading on the returnvalue]
> I've read a lot of (pseudo) arguments why this fact is a must. (I
> disagree with (almost) all of them (as far as I remember). Anyway: it
> is like it is.)

Hmmm, the main issue is that you can choose to ignore the returnvalue,
leaving the compiler with no way to actually figure out which overload you
wanted.

That said, you _can_ have a function overloaded by the returntype and I
actually use that a lot. The simple solution is to have a template
parameter. Then, you you simply say it explicitly which overload you want:

int x = parse(some_string);
float f = boost::lexical_cast(another_string);
char* c = reinterpret_cast(42);

Okay, the last one is actually not an overloaded function, but I like the
similarity of the syntax.

> struct TestFunky
> {
> int val;
> char chr;
> TestFunky( int v, char c)
> : val(v)
> , chr(c)
> {}
> };
> class funky
> {
> TestFunky& tf_;
> public:
> funky(TestFunky& tf)
> : tf_(tf)
> {}
>
> operator int()
> {
> return tf_.val;
> }
>
> operator char()
> {
> return tf_.chr;
> }
> };
> TestFunky testy( 666, 'E');
> // and so we do as we wanted to.
> int i = funky(testy);
> char c = funky(testy);

A bit complicated for my taste...

> // .and it even doesn't need more CPU load! (If the compiler isn't too
> dumb.)

Really? You first need both the 666 and the 'E', which are IIUC the results
of the two function calls, so typically one of them is wasted. That's also
why I'd use a less complicated one:

int int_function();
char char_function();

struct proxy {
operator int() const {
return int_function();
}
operator char() const {
return char_function();
}
};

proxy function() {
return proxy();
}

Here, you only have a single proxy object that call one of the functions on
demand, depending on which conversion is requested.


> Of course
> <.
> funky(testy); // doesn't work
> .>

The problem here is that the actual function isn't called (my code) or both
are called (your code). In some cases I can actually live with that or a
runtime error.

Uli

--
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

SFINAE?

Hi,

korben dallas wrote:
> Hello
>
> Please, consider the following code sample
>
> template void foo(const T&, char(*)[sizeof(T) - 1] = 0);
>
> int foo(...);
>
> int main()
> {
> char c;
> return foo(c);
> }
>

[...]

>
> However, if I change the template declaration to
>
> template int foo(const T&, char[sizeof(T) - 1] = 0);
>
> Comeau complains with
>
> error: the size of an array must be greater than zero
> int foo(const T&, char[sizeof(T) - 1] = 0);
> ^
> detected during instantiation of "foo" based on template
> argument


I've been reading the standard, and from what I can see - is it possible
that Comeau has a bug?


1) We don't deduce the type from the default argument.

14.8.2.4/17: A template-type parameter cannot be deduced from the type
of a function default argument.


2) For an explicitly specified argument, deduction fails for an array
size that is zero.

14.8.2/2b3b1: Attempting to create an array with an element type that
is void, a function type, or a reference type, or attempting to create
an array with an array size that is zero or negative.


3) Unfortunately here is where it gets a bit shaky:

14.8.2/4: The resulting substituted and adjusted function type is used
as the type of the function template for template argument deduction.
When all template arguments have been deduced, all uses of template
parameters in nondeduced contexts are replaced with the corresponding
deduced argument values. If the substitution results in an invalid type,
*** as described above ***, type deduction fails. [Emphasis is mine]

What is being referred to by "as describe above"? If this refers back
to 14.8.2/2 then it means that after deduction the rules for explicit
arguments also apply to the deduced arguments in the non-deduced
contexts. In which case, the array with zero size is a deduction failure.


After arriving at the above, I then tested to see what happens in Comeau
when you explicitly specify the arguments:

template void f1(const T&, char(*)[sizeof(T) - 1] = 0);
template void f1(const T&, char[sizeof(T) - 1] = 0);
template int f1(...);

int main()
{
char c;
f1(c);
}

Comeau still fails to compile this example - but I think it is clear
from 14.8.2/2b3b1 that it should just fail "deduction"?





Regards,

Richard




--
Richard Corden

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?

Mathias Gaunard wrote:
> On 23 sep, 14:28, Andrei Alexandrescu
> wrote:
>
>> That's pretty much why I dislike the term zombie for a terminated
>> object. To me that object should be eminently usable, just that it is in
>> an empty state where it consumes no resources beyond its own bits.
>
> Several proprieties of the object will only be available when the
> object is not empty. Therefore you will have to generate errors (most
> likely asserts, but some like to use exceptions) if some code attempt
> to access the resource that doesn't exist anymore.
> On the other hand, not allowing that empty state gives you the
> invariant that no such error can occur.

Clearly not allowing the empty state gives you a stronger invariant. I
am not contending that. But that approach has a hard time when it comes
about accessing objects that have been destroyed (and therefore did
enter an empty state).

> Your empty states may be better than dangling pointers, but not much
> better, since they really are like null pointers.

I do think that null pointers are progress compared to dangling
pointers. Also, empty states are more than null pointers. They can be
functional and informative the same way an empty vector is more
functional and more informative than a null pointer.


Andrei

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Creating a function object that chains multiple actions?

francis_r ha scritto:
> How can I bundle multiple actions together into one function object?
>
> For example, I would like to be able to do this:
>
> Window * myWindow;
> boost::function showWindowFunction = make_function_sequence(
> boost::bind(&Window::setVisible, myWindow, true),
> boost::bind(&Window::positionInMiddleOfScreen, myWindow)
> );
>

struct function_sequence
{
boost::function first, second;

function_sequence(
boost::function f,
boost::function s)
: first(f), second(s)
{}

void operator()() const
{
first();
second();
}
};

HTH,

Ganesh

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

getting started with lambda function in boost

Searching for very good but simple explanation of lambda functions in c
++ using boost lambda library . Just started reading boost
documentation .Any other good documents,article,url is highly
appreciated

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?

On 23 sep, 02:33, Andre Kaufmann wrote:

> Well, depends on the overall code size. Which is the compiler, which has
> that well optimized, table based, exception handling ? I would like to
> have a look at the generated assembly code.

Virtually all recent compilers but Windows ones follow the Itanium
ABI, since it is the only platform-independent C++ ABI standard.
Windows has its own ABI, so compilers tend to follow it on that
platform.

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

C++0x: New function syntax; opportunity to fix arrays?

On Sep 23, 1:58 am, Marsh Ray wrote:
> Without array-to-pointer decay, how would
>
> printf("Hello, world!\n");
>
> have compiled?

I do not propose to remove the implicit conversion from array to
pointer (see my reply to Lapin), but you bring up an interesting
issue.

The general solution to this problem should have been simple: just
overload and forward:

template
int printf (const char (&s) [N], Args... args)
{return printf (&s [0], args...);}

Unfortunately this doesn't work due to the current overloading rules
in C++. An array-to-pointer conversion is ranked as an "exact match"
while searching for viable functions (§13.3.3.1 Implicit conversion
sequences). Thus two overloads, one taking a pointer and the other an
array, are ambiguous:

void foo (const char* a); // #1

void foo (const char (&a) [7]); // #2

void test () {foo ("Hello!");} // ambiguous

This is unfortunate. In my view #2 should be preferred. This could be
resolved by introducing a lower ranking for the array-to-pointer
conversion.

Unfortunately, it gets worse. Another C++ rule (§13.3.3) says that a
non-template function is preferred over a template function
specialization when both candidates are equally good (judged by the
implicit conversion sequence ranking). That means that an intuitively
worse match (pointer) is preferred over an intuitively better match
(array):

void foo (const char* a); // #1

template
void foo (const char (&a) [N]); // #2

void test () {foo ("Hello!");} // calls #1!

Sadly, this means that a fix to the ranking is unlikely. It would
break existing code in the worst manner; code would change behaviour.

Regards,
Vidar Hasfjord


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Creating a function object that chains multiple actions?

On Sep 23, 2:25 am, francis_r wrote:
> How can I bundle multiple actions together into one function object?
>

I found a little workaround:

void foo()
{
Window * myWindow;

struct Helper // defined in function scope
{
static showWindow(Window* inWindow)
{
inWindow->setVisible(true);
inWindow->positioninMiddleOfScreen();
}
}
boost::function showWindowFunction =
boost::bind(Helper::showWindow, myWindow);

);

This way of working seems to be a simple workaround for the more
complex boost::lamda library.

Do you think it is a good practice?


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Looking for multi-thread program codes

Hello,

I am now studying C++ multi-thread programming (phtread) for high
performance computing course, I want to see some usable sources codes
and learn from them!

Are there any recommended site contains these example for me to study?

Thanks.

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

How to Call "Constructor with parameter" after new [] allocation?

On 23 sep, 02:27, Mathias Gaunard wrote:

> _test* t2 = ::operator new(sizeof(_test)*2);


This of course doesn't compile, since it returns a void*. Adding a
static_cast should be sufficient.


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google

Are throwing default constructors bad style, and if so, why?

Andre Kaufmann wrote:
> JoshuaMaurice@gmail.com wrote:
>> [...]
>> This is the way they used to be implemented. For example, Visual
>> Studios 2003 implements it that way.
>>
>> On any good compiler, during normal course of operation, there is
>
> Hm, implies the previous compiler isn't quite good ?
> By the way this compiler eventually had to track non linear control flow
> too, caused by raised structured exceptions (which are not standard C++).
>
>> absolutely no additional work. When an exception is thrown, it goes to
>> a global lookup table based on the current program counter value. This
>> table is built at compile time. Each entry points to a block of code
>
> Can you really map each line of code to a static lookup table, without
> keeping track which object has been constructed or not ?
>
> One (lame) example:
>
> void foo()
> {
>
> if (a) goto v2;
> v1:
> object a1;
> v2:
> object a2;
> v3:
> }
>
> How does (such a) the compiler know at v3: if object a1() has been
> constructed or not ?

I thought that code was ill formed because of the jump over and the
construction of a1.

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google