gpt4 book ai didi

C++ 适当的结构初始化

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:36:28 25 4
gpt4 key购买 nike

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

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

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* 关于内存分配,我想知道在 addConnection()< 中初始化新的 connectionElement 的正确方法是什么/em>。

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

最佳答案

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?

不,在您的代码段中,类 ConnectionData 拥有其数据成员 connections, vector 中的元素按值存储。因此,只要它所属的类实例存在,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});

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

关于C++ 适当的结构初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52357026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com