传递值或const引用的函数? [英] Pass by value or const reference to function?

查看:137
本文介绍了传递值或const引用的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该通过值或通过引用一个函数传递 std :: string 。此函数将此值存储在类的成员变量中。

Should I pass std::string by value or by reference to one function. This function store this values in member variable of class.

我总是混淆当通过值或引用时。请清除我对此的混淆。

I am always confuse when about pass by value or reference. Please clear my confusion about this.

以下是代码:

class DataStore {
public:
    void addFile(const string& filename, const set< std::string>& filePaths)
    {  
        if (dataStoreMap.insert(make_pair(filename, filePaths)).second)
        {
            cout << "Data Added" <<endl;
        }
        else
        {
            cout << "Data not Added" << endl;
        }
    }
private:
    // member variable
    map < string, set < string >  > dataStoreMap;
};

我应该这样做函数声明:

Shall I make function declaration like this :

void addFile(const string& filename, const set< std::string>& filePaths)

void addFile(const string filename, const set< std::string> filePaths)

两者都给出相同的结果。如果有关于内存分配或性能的任何问题。

Both gives same result. If there any issue about memory allocation or performance.

cpp 类调用上述函数。

DataStore ds;
set<string> setFileDirectory{ "1", "2", "3", "4", "6", "5" };
ds.addFile("file.txt", setFileDirectory);

setFileDirectory.erase(setFileDirectory.begin(), setFileDirectory.end());
setFileDirectory.insert({ "1", "2", "3", "4", "5", "6" });
ds.addFile("demo.txt", setFileDirectory);

任何详细说明都将不胜感激。

Any detailed explanation would be appreciated.

感谢

推荐答案

当您有输入参数时, / em>修改,并考虑通过 const reference const& )将其传递给避免无用的深层副本(可能需要动态内存分配等)

When you have an input parameter, i.e. something that is observed by the function and not modified, consider passing it by const reference (const &), to avoid useless deep-copies (which may require dynamic memory allocations, etc.)

void addFile(const std::string& filename, 
             const std::set<std::string>& filePaths)






PS

当然,如果您传递便于复制的参数,例如 int s,你只需传递值:)


P.S.
Of course, if you are passing parameters that are cheap to copy, like ints, you can just pass by value :)

这篇关于传递值或const引用的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆