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

pan*_*ajt 1 c++ coding-style

我有一个大对象说MyApplicationContext,它保存有关MyApplication的信息,如名称,路径,loginInformation,描述,详细信息等.

// MyApplicationCtx

class MyApplicationCtx{
       // ....
    private:
        std::string name;
        std::string path;
        std::string desciption;
        struct loginInformation loginInfo;
        int appVersion;
        std::string appPresident;
        //others
}
Run Code Online (Sandbox Code Playgroud)

这是我的方法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.
Run Code Online (Sandbox Code Playgroud)

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

Q2.如果我使用引用传递它,那么对性能的影响应该是什么?

public void setAppLoginInformation(MyApplicationCtx &appObj){ 
    this->loginInfo = appObj.loginInfo;
}
Run Code Online (Sandbox Code Playgroud)

//代码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);
}
Run Code Online (Sandbox Code Playgroud)

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

luk*_*uke 15

你最好定义一个Copy Constructor和一个赋值运算符:

// 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);
Run Code Online (Sandbox Code Playgroud)

更好的是,还要在类中定义一个私有结构,如下所示:

struct AppInfo
{
    std::string name;
    std::string path;
    std::string desciption;
    struct loginInformation loginInfo;
    int appVersion;
    std::string appPresident;
};
Run Code Online (Sandbox Code Playgroud)

在App类的复制构造函数和赋值运算符中,您可以利用AppInfo自动生成的赋值运算符为您执行所有赋值.这假设您只希望MyApplicationCtx在"克隆"时复制一部分成员.

如果您添加或删除AppInfo结构的成员而不必更改所有样板,这也将自动更正.