gpt4 book ai didi

c++ - C++ 中的编码实践,您的选择是什么,为什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:06:25 25 4
gpt4 key购买 nike

我有一个大对象 MyApplicationContext,它保存有关 MyApplication 的信息,例如名称、路径、登录信息、描述、详细信息等。

//MyApplicationCtx

class MyApplicationCtx{
// ....
private:
std::string name;
std::string path;
std::string desciption;
struct loginInformation loginInfo;
int appVersion;
std::string appPresident;
//others
}

这是我的方法 cloneApplication(),它实际上设置了一个新的应用程序。如代码 1 和代码 2 所示,有两种方法可以做到这一点。我应该更喜欢哪一种,为什么?

//代码1

public void cloneApplication(MyApplicationCtx appObj){
setAppName(appObj);
setAppPath(appObj);
setAppAddress(&appObj); // Note this address is passed
setAppDescription(appObj);
setAppLoginInformation(appObj);
setAppVersion(appObj);
setAppPresident(appObj);
}

public void setAppLoginInformation(MyApplicationCtx appObj){
this->loginInfo = appObj.loginInfo; //assume it is correct
}

public void setAppAddress(MyApplicationCtx *appObj){
this->address = appObj->address;
}

.... // same way other setAppXXX(appObj) methods are called.

Q1. 每次传递大对象 appObj 是否会对性能产生影响?

Q2.如果我使用引用传递它,对性能有什么影响?

public void setAppLoginInformation(MyApplicationCtx &appObj){ 
this->loginInfo = appObj.loginInfo;
}

//代码2

public void setUpApplication(MyApplicationCtx appObj){
std::string appName;
appName += appOj.getName();
appName += "myname";
setAppName(appName);

std::string appPath;
appPath += appObj.getPath();
appPath += "myname";
setAppPath(appPath);

std::string appaddress;
appaddress += appObj.getAppAddress();
appaddress += "myname";
setAppAddress(appaddress);

... same way setup the string for description and pass it to function
setAppDescription(appdescription);

struct loginInformation loginInfo = appObj.getLoginInfo();
setAppLoginInformation(loginInfo);

... similarly appVersion
setAppVersion(appVersion);
... similarly appPresident
setAppPresident(appPresident);
}

Q3.比较代码1和代码2,我应该使用哪一个?我个人喜欢代码 1

最佳答案

你最好定义一个 Copy Constructor和一个 Assignment Operator :

// Note the use of passing by const reference!  This avoids the overhead of copying the object in the function call.
MyApplicationCtx(const MyApplicationCtx& other);
MyApplicationCtx& operator = (const MyApplicationCtx& other);

更好的是,还可以在类中定义一个私有(private)结构,如下所示:

struct AppInfo
{
std::string name;
std::string path;
std::string desciption;
struct loginInformation loginInfo;
int appVersion;
std::string appPresident;
};

在您的 App 类的复制构造函数和赋值运算符中,您可以利用 AppInfo 自动生成的赋值运算符为您完成所有赋值操作。这是假设您只希望在“克隆”时复制 MyApplicationCtx 成员的一个子集。

如果您添加或删除 AppInfo 结构的成员而无需更改所有样板文件,这也将自动正确。

关于c++ - C++ 中的编码实践,您的选择是什么,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1716485/

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