Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ proper structure initialization

I'm sorry to ask another newbie question, but google could'nt quite help me (or maybe I just didn't understand it).

I'm trying to code a class that is capable of storing some simple connection data. My early concept looks like the following:

struct connectionElement{
 string ip;
 SOCKET soc;
};

class ConnectionData{
 private:
  vector<connectionElement> connections;

 public:
  ConnectionData();
  ~ConnectionData();

  void addConnection(string ip, SOCKET soc);
};

void ConnectionData::addConnection(string ip, SOCKET soc) {
 connectionElement newElement;
 newElement.ip = ip;
 newElement.soc = soc;
 connections.push_back(newElement);
 return;
}

Now I've read that objects being initialized without the use of new will be delocated once the code reaches the end of scope. So since I'm a java guy and don't know shi* about memory allocation, I was wondering what the correct way'd be to to initialize the new connectionElement in addConnection().

Do I have to use new in order to prevent the data from being deleted or does the compiler assume that a stored structure might be accessed again later on? And if I use the new operator do I have to delete all the objects manually before the thread terminates or does that happen automatically?

like image 642
Flo Avatar asked Sep 16 '18 18:09

Flo


1 Answers

Do I have to use new in order to prevent the data from being deleted or does the compiler assume that a stored structure might be accessed again later on?

No, in your snippet, the class ConnectionData owns its data member connections, and the elements in the vector are stored by value. Hence, connections is existant as long as its owning class instance exists:

void someFunctionInYourProgram()
{
    ConnectionData example{};

    example.addConection(/* ... */);

    // do stuff with the ConnectionData instance and its connections

    void doMoreStuffWith(example);

 } // Now, example went out of scope, everything is automatically cleaned up.

And if I use the new operator do I have to delete all the objects manually before the thread terminates or does that happen automatically?

If you allocate objects with new and don't pass the raw pointer returned to some smart poiter taking care of its deletion, you must indeed manually clean it up with delete. But there shouldn't be too many situation where this applies, as std::shared_ptr and std::unique_ptr are there to the rescue, and they ship with std::make_shared and std::make_unique, which even makes it obsolete to manually invoke the new operator.

One last note on this snippet

connectionElement newElement;
newElement.ip = ip;
newElement.soc = soc;
connections.push_back(newElement);

You can simplify this to

connections.push_back({ip, soc});

which might save a copy construction (if not already optimized out by the compiler).

like image 52
lubgr Avatar answered Sep 18 '22 02:09

lubgr