Re: A problem with g++ compiler
On 2 Nov., 02:18, luca wrote:
typedef struct mystruct_t
{
int v1, v2;
unsigned char *v3;
// constructor
mystruct_t( int p_v1, int p_v2, unsigned char *p_v3)
: v1(p_v1), v2(p_v2), v3(p_v3)
{}
} mystruct_t;
In C++ you don't need typedef for this.
and the following class:
class MyClass
{
public:
static myfunc(mystruct_t &m);
};
This static member function declaration is missing a return type.
Somewhere in my code i have the following line:
// ..
MyClass::myfunc(mystruct_t(1, 2, NULL));
It compile with Visual C/C++ , but when i try to compile it with g++
(using linux Mandriva + Eclipse IDE), i get the following error:
no matching function for call to 'MyClass::myfunc(mystruct_t &) '
I can't really understand why g++ can't compile that line.
This line of code is not valid C++. So, g++ doesn't have to accept it.
Non-const references cannot be initialized with an rvalue expression.
But your initializer is an rvalue expression. The Microsoft compiler
accepts this as an extension. You can disable this language extension
with the appropriate compiler option so that it also rejects the code.
The famous motivating example to disallow binding non-const references
to temporary objects is this:
void inc(long & i) {
++i;
}
int main() {
int k = 23;
inc(k);
cout << k << endl;
}
Augmented with the appropriate include and using directives this
program will still not compile. A conversion from the int k to a long
would yield an rvalue. If the reference were allowed to bind to that
temporary object, the program would still output 23 because the
original object is not modified but only the temporary int.
If you don't intent do modify the object you can write instead:
void inc(long const& i) {
}
and this will be fine. Applied on your example:
class MyClass
{
public:
static void myfunc(mystruct_t const& m);
}; // ^^^^^
This should compile. There is little danger in binding a reference-to-
const to a temporary object.
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]