0

NewSocketException():

SocketException NewSocketException(string callstack,Socket* socket)
{
    SocketException se;
    se.callStack = callstack;
    se.message = GetLastWinsockErrorMessage(&se.code);
    if (socket != nullptr)
        se.socket = new Socket(*socket);
    return se;
}

NewSocketException() should make SocketException struct for me and return it. C++ calls se.~SocketException() (it deletes se.socket) when return se; is executed. I guess that's because se goes out of scope but it's returned also so I don't know exactly what is going on over here. When this line is done:

 SocketException se = NewSocketException("accept() in AcceptThread()",server);

se contains correct strings (by stepping into I noticed that strings are also being destroyed by ~basic_string() but they are still there when function returns) and correct (the same) pointer value but objet (se.socket) is still destroyed. Why destructor is being called ? Why my object is gone and strings are still there ?

Maciej Szpakowski
  • 571
  • 1
  • 7
  • 22
  • *Why is the destructor being called?* Because the lifetime of the local object has ended. *Why are the objects still there?* Because [the hotel does not guarantee it will remove the stuff you left in the drawer immediately after you check out of your room](http://stackoverflow.com/q/6441218/50079). – Jon May 22 '15 at 20:55
  • Once you decrypt how the linked answer is related to your question, consider that by your own example you're violating the [Rule of Three](http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29). – WhozCraig May 22 '15 at 21:02
  • At some point you think that you know a lot and heard a lot and something like this happens and you realize that you barely scratched the surface. – Maciej Szpakowski May 22 '15 at 21:09

1 Answers1

1

You are returning a local variable sefrom function, and its scope ends when your code reach last brace of the function. So it will call the destroctor.

To resolve the issue define a variable before calling the function and pass it as argument to your function.

SocketException se;

void NewSocketException(string callstack,Socket* socket, SocketException &se)
{

    se.callStack = callstack;
    se.message = GetLastWinsockErrorMessage(&se.code);
    if (socket != nullptr)
        se.socket = new Socket(*socket);
 }
Steephen
  • 14,645
  • 7
  • 40
  • 47