C++ 通过别名返回变量,而不在函数分配后动态分配或删除

C++ 通过别名返回变量,而不在函数分配后动态分配或删除,c++,oop,C++,Oop,我为用户定义的StringSet类重载了+运算符,它将两个StringSet合并在一起 StringSet& StringSet::operator+(StringSet& set2) { StringSet* temp = new StringSet; for (auto i = 0; i < this->getSize(); i++) { temp->addSet(this->data[i]);

我为用户定义的StringSet类重载了+运算符,它将两个StringSet合并在一起

StringSet& StringSet::operator+(StringSet& set2) {
    StringSet* temp = new StringSet;
    for (auto i = 0; i < this->getSize(); i++) {
        temp->addSet(this->data[i]);             
    }
    for (auto j = 0; j < set2.getSize(); j++) {
        temp->addSet(set2.data[j]);              
    }
    return *temp;
}
StringSet&StringSet::operator+(StringSet&set2){
StringSet*temp=新的StringSet;
对于(自动i=0;igetSize();i++){
临时->添加集(此->数据[i]);
}
对于(自动j=0;jaddSet(set2.data[j]);
}
返回*温度;
}
如果我不动态分配temp,我将无法将其用作

cout << "union is: " << s1+s2 << endl;    // s1 and s2 are StringSet objs created using constructor

cout动态分配在这里是完全错误的。您需要按值返回:


为移动提供额外的重载可能会提高性能(请参阅此)

在这种情况下,可以使用右值引用实现重载+运算符,如下所示:

StringSet&& StringSet::operator+(StringSet&& set2) {
    StringSet temp;
    for (auto i = 0; i < this->getSize(); i++) {
        temp.addSet(this->data[i]);             
    }
    for (auto j = 0; j < set2.getSize(); j++) {
        temp.addSet(set2.data[j]);              
    }
    return std::move(temp);
}
StringSet&&StringSet::operator+(StringSet&&set2){
设置温度;
对于(自动i=0;igetSize();i++){
临时添加集(此->数据[i]);
}
对于(自动j=0;j
如果要就地执行
+
操作,应重载
运算符+=
而不是
运算符+
,但按值返回不支持concatenation@letsShareKnowlede你这么说是什么意思?我的意思是,如果函数是按值返回的,那么这行“cout@letsShareKnowlede No,那行当然可以(这就是重点),你怎么会认为它不会呢?如果代码中的行不起作用,那么这是因为在
操作符中没有将对象作为
const&
传递所致
StringSet StringSet::operator+(StringSet const& other) const {
    auto result = *this; // This invokes the copy constructor!
    return result += other;
}

StringSet& StringSet::operator+=(StringSet const& other) {
    for (auto i = 0; i < other.getSize(); ++i) {
        addSet(other.data[i]);
    }
    return *this;
}
StringSet&& StringSet::operator+(StringSet&& set2) {
    StringSet temp;
    for (auto i = 0; i < this->getSize(); i++) {
        temp.addSet(this->data[i]);             
    }
    for (auto j = 0; j < set2.getSize(); j++) {
        temp.addSet(set2.data[j]);              
    }
    return std::move(temp);
}