Exception & copy constructor

A

Adam

Why does this compile:

if (err != Socket::errSuccess) {
switch (err) {
case Socket::errTimeout:
ConnectionIOException cio(new
string(myTCPStream->getErrorString()), ConnectionIOException::TIMEOUT);
throw cio;

default:
ConnectionIOException cio(new
string(myTCPStream->getErrorString()), ConnectionIOException::GENERAL);
throw cio;

}
}

and this not:

if (err != Socket::errSuccess) {
switch (err) {
case Socket::errTimeout:
throw ConnectionIOException (new
string(myTCPStream->getErrorString()), ConnectionIOException::TIMEOUT);

default:
throw ConnectionIOException (new
string(myTCPStream->getErrorString()), ConnectionIOException::GENERAL);


}
}

with this error:

Connection.cpp:85: error: no matching function for call to
`ConnectionIOException::ConnectionIOException(ConnectionIOException)'
.../exceptions/ConnectionIOException.h:19: note: candidates are:
ConnectionIOException::ConnectionIOException(ConnectionIOException&)
Connection.cpp:85: error: in thrown expression
Connection.cpp:88: error: no matching function for call to
`ConnectionIOException::ConnectionIOException(ConnectionIOException)'
.../exceptions/ConnectionIOException.h:19: note: candidates are:
ConnectionIOException::ConnectionIOException(ConnectionIOException&)
Connection.cpp:88: error: in thrown expression

Thanks,

Adam
 
D

Dietmar Kuehl

Adam said:
Why does this compile:
ConnectionIOException cio(new
string(myTCPStream->getErrorString()), ConnectionIOException::TIMEOUT);
throw cio;

This copies the exception from the [non-const] object 'cio'. Thus,
a copy constructor of the form

| ConnectionIOException(ConnectionIOException&);

is sufficient.
throw ConnectionIOException (new
string(myTCPStream->getErrorString()),
ConnectionIOException::TIMEOUT);

This, on the other hand, try to copy the temporary and thus requires
a copy constructor of the form

| ConnectionIOException(ConnectionIOException const&);

because temporaries cannot be bound to a non-const reference. The error
message exposes that you don't have a copy constructor taking a const
object as parameter:
 

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

No members online now.

Forum statistics

Threads
474,197
Messages
2,571,040
Members
47,635
Latest member
SkyePurves

Latest Threads

Top