C++ 适当的结构初始化

C++ proper structure initialization

很抱歉又问了一个新手问题,但是google帮不了我(或者我只是不明白)。

我正在尝试编写一个能够存储一些简单连接数据的 class。我的早期概念如下所示:

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;
}

现在我读到,一旦代码到达范围末尾,不使用 new 初始化的对象将被释放。所以因为我是一个 java 的人并且不知道 shi* 关于内存分配,我想知道初始化新的 connectionElement 的正确方法是什么addConnection()

我是否必须使用 new 以防止数据被删除,或者编译器是否假定稍后可能会再次访问存储的结构?如果我使用 new 运算符,我是否必须在线程终止之前手动删除所有对象,还是自动删除?

您的代码有效!

vector.push_back()

复制对象,因此整个结构的副本将存在于连接向量中。

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?

不,在您的代码段中,class ConnectionData 拥有其数据成员 connections,向量中的元素按值存储。因此,只要其拥有的 class 实例存在,connections 就存在:

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?

如果您使用 new 分配对象并且不将返回的原始指针传递给负责删除的智能指针,您确实必须使用 delete 手动清理它。但是不应该有太多的情况适用于此,因为 std::shared_ptrstd::unique_ptr 可以救援,并且它们附带 std::make_sharedstd::make_unique,这甚至使得手动调用 new 运算符已经过时了。

关于这个片段的最后一个注释

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

您可以将其简化为

connections.push_back({ip, soc});

这可能会保存一个副本构造(如果编译器尚未优化的话)。