For exemple, say that I have a Game class:
class Game{
public:
Game();
~Game();
void CreateWindowClass(HINSTANCE);
void CreateRessources(HINSTANCE);
void ShowMainScreen();
Winsock* CreateWinsock();
MessageLog* CreateMessageLog();
D2DResources* CreateD2DResources(HWND);
HWND Getm_hWnd();
public:
D2DResources* pD2DResources;
Winsock* pWinsock;
MessageLog* pMessageLog;
private:
HWND m_hWnd;
};
and the 3 pointers inside Game are assigned like this:
Winsock* Game::CreateWinsock()
{
pWinsock = new Winsock;
return pWinsock;
}
Will this cause any problem? Also, will I delete the dynamically created object like this: delete pWinsock;?
pWinsock
is a public member, but either way there is nothing wrong with this. Both pWinsock
and the pointer return value of the function are pointing at the dynamically allocated Winsock
object. As long as you delete
the object at some point, you don't have a memory leak.
The only issue here is that the client of this function may delete
the pointer themselves, while your Game
object might rely on the pWinsock
pointer being valid for a particular duration (perhaps for its entire lifetime). You can best express your intent by using a smart pointer. A std::shared_ptr<Winsock>
would be a good choice here, as your Game
object creates the Winsock
and then shares ownership with the client.
I would avoid exposing public fields and sharing raw pointers like that. You're breaking encapsulation and making memory management more difficult. Instead use accessor/mutator functions, as in Java. The compiler will inline these away.
The problem with returning the Winsock*
from CreateWinsock
is that it isn't clear who "owns" the Winsock object anymore, since the method resembles a factory constructor, where the caller owns it, but you're setting a member field to it, so the host Game
object really owns it.
I suggest using a smart-pointer like shared_ptr
when exposing the Winsock object so the lifetime of the Winsock is controlled.
The Winsock
object will not be deleted automatically unless you delete it from within your Game::~Game()
destructor.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.