No warning about accidental cast(?)

me22 me22.ca@gmail.com
Tue Jun 12 15:28:00 GMT 2007


On 12/06/07, Arend-Jan Wijtzes <ajwytzes@wise-guys.nl> wrote:
> But what puzzles me is that I can actually declare a nameless object like that.
> For example the analogy with int would be:
>
> int main()
> {
>         int;
> }
>
> which gives the error: "error: declaration does not declare anything".
>
The analog for int would be int(), which is semantically the same as 0.

> Now I'm not advocating that this should be an error for classes, but it would
> be nice if there was some mechanism to warn about this. How likely is it that
> an author actually intends to create an object and immediately destroy it again
> in one line of code, without doing anything with it?
>
In the simple examples, very unlikely.

However, you can do some fun things thanks to the lifetimes of temporaries:

#include <iostream>
struct output_wrapper {
    output_wrapper() { std::cout << "PRELUDE\n"; }
    ~output_wrapper() { std::cout << "POSTLUDE\n" << std::flush; }
};
int main() {
    output_wrapper(), std::cout << "Hello World" << std::endl;
}

Admittedly contrived, but I'm sure you can come up with your own fun
abuses.  Maybe use it with scoped_lock to lock for a single statement
without needing to create a block or think up a name the lock object?

~ Scott McMurray



More information about the Gcc-help mailing list