Use of explicit

F

Fred Zwarts

Consider the following code:

// Start of code

class MyException_t {

public:

// Default constructor.

inline explicit MyException_t () {}

// Initializer constructor.

inline explicit MyException_t (const MyException_t &E) {}

};

int main () { // I know, it needs parameters, that's not my point now.

MyException_t E;
throw E;

}

// End of code

Most compilers have no problem with it, but one compiler shows the following error message:

ppc_60x-g++ -static Except.cpp -o Except
Except.cpp: In function `int main()':
Except.cpp:18: error: no matching function for call to `MyException_t::MyException_t(MyException_t&)'
Except.cpp:18: error: in thrown expression

However, if the "explicit" keywords are remove, it compiles without problem.
Which of the compilers are following the C++ standard?,
The compilers that compile the code with the explicit keyword without error messages,
or the compiler that generates the error messages?

Regards,
Fred.Zwarts.
 
D

Dietmar Kuehl

Fred said:
class MyException_t {
public:
// Default constructor.
inline explicit MyException_t () {}

// Initializer constructor.
inline explicit MyException_t (const MyException_t &E) {}
};

Both of these constructors are only used with "direct-initialization
syntax" or with explicit casts. They are not used to implicitly
create an object as is needed e.g. to copy an exception thrown.

BTW, the more conventional name for your "initializer constructor"
is "copy constructor".
MyException_t E;
throw E;

The throw statement requires a viable copy constructor. However,
your copy constructor requires either an explicit cast or the
use of direct-initialization to be used and is thus not viable.
The use of 'explicit' on a copy constructor is not buying you much
anyway: the copy constructor is not used for any conversions and
the only aspect of 'explicit' is to suppress use of constructors
for implicit conversions. Thus, the correct fix is to drop the
'explicit' keyword from your copy constructor.

BTW, EDG front-end based compilers also reject your code.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,967
Members
47,520
Latest member
KrisMacono

Latest Threads

Top