简体   繁体   English

C++ 使用 function 初始化结构

[英]C++ struct initialization with a function

I'm dealing with the following situation:我正在处理以下情况:

Struct Data;
typedef std::shared_ptr<Data> DataPtr;
typedef std::unordered_map<int, DataPtr> DataPtrMap;

DataPtrMap data;
std::string file_path;

I need to create an empty DataPtrMap and initialize it from file with a function that takes the file path as an input.我需要创建一个空的DataPtrMap并使用将文件路径作为输入的 function 从文件初始化它。 Essentially, this function reads the file line-by-line, creates a new struct , fills it with data and inserts it in the unordered_map .本质上,这个 function 逐行读取文件,创建一个新struct ,用数据填充它并将其插入unordered_map The Data structure contains just some integers and a couple of small matrices, and there can be up to a few thousands of them in the unordered_map . Data结构只包含一些整数和几个小矩阵,在unordered_map中最多可以有几千个。 I'm wondering whether it's more efficient to pass a pointer to the (initially empty) data as input to the function as:我想知道将指向(最初为空的)数据的指针作为输入传递给 function 是否更有效:

void loadData(DataPtrMap*, const std::string&);
loadData(&data, file_path);

or if it's better to directly return it from the function as:或者如果最好直接从 function 返回它:

DataPtrMap loadData(const std::string&);
data = loadData(file_path);

My intuition is that the second solution is much cleaner in terms of readability and return value optimization should avoid making a useless copy of the data when returning from the function.我的直觉是,第二种解决方案在可读性和返回值优化方面更清晰,应该避免在从 function 返回时制作无用的数据副本。 However, I would like to have the opinion of more expert coders.但是,我想听听更多专家编码员的意见。

Thank you in advance for the help.预先感谢您的帮助。

To avoid the use of raw pointer in your case you can use references in your option1:为避免在您的情况下使用原始指针,您可以在 option1 中使用引用:

void loadData(DataPtrMap&, const std::string&);
loadData(data, file_path);

With references the first option is clean and needs no more optimization to avoid unnecessary copy.使用引用,第一个选项是干净的,不需要更多优化以避免不必要的复制。

I like the syntax of option2 but your need to take care of optimizing copy.我喜欢 option2 的语法,但您需要注意优化副本。 But like jfh said, optimization is the last step when coding, do not bother with that at the beginning但是就像 jfh 说的,优化是编码的最后一步,不要一开始就在意

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM