c++ - 返回引用实例和非引用实例之间有什么区别(return mystr & vs mystr)?

标签 c++

<分区>

这里是mystr结构

#include <stdio.h>
#include <string.h>

struct mystr {
    char *str;

    mystr(const char *s) {
        str = new char[strlen(s) + 1];
        strcpy(str, s);
        printf("[1]%s\n", s);
    }

    mystr(const mystr &s) {
        str = new char[strlen(s.str) + 1];
        strcpy(str, s.str);
    }

    ~mystr() {
        delete[] str;
    }

    void printn() const {
        printf("%s\n", str);
    }

    //mystr& operator+=(const char *s) this line works!
    mystr operator+=(const char *s) {
        char *old = str;
        int len = strlen(str) + strlen(s);
        str = new char[len + 1];
        strcpy(str, old);
        strcat(str, s);
        printf("[2]%s,%s,%s\n", old, s, str);
        delete[] old;
        return *this;
    }
};

这里是主要代码

int main() {
    mystr s = "abc";
    (s += "def") += "ghi";
    // only print  s = abcdef
    // when put & before operator+=, it prints s = abcdefghi
    printf("s = %s\n", s.str); 
}

问题

有什么区别 返回 mystr & vs mystr? 我看到 operator+= 被调用了两次,但输出不同。 在 C++ 中返回实例有什么行为?

最佳答案

区别在于您返回的是拷贝还是引用。

有了这个:

mystr operator+=(const char*) {/* some code */ return *this;}

你返回一个this对象的拷贝。

有了这个:

mystr& operator+=(const char*) {/* some code */ return *this;}

您返回对this 对象的引用。

当您退回拷贝时:

(s += "def") += "ghi";

不将 "ghi" 添加到 s,而是添加到它的拷贝,保持 s 不变。

您可以让您的 mystr(const mystr &s) 复制构造函数(并且可能是析构函数)也打印出一些东西以查看差异。

关于c++ - 返回引用实例和非引用实例之间有什么区别(return mystr & vs mystr)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59621426/

上一篇:c++ - 在开关盒内阻塞

下一篇:c# - 在 c++ 管理和异步运行中调用 c# 可执行文件

相关文章:

c++ - 为什么这会导致缓冲区溢出?

c++ - 转换到子对象进行测试 - 此代码是否符合标准?

c++ - 如何在 C++ 中散列

c++ - 如何在 c 或 c++ 语言 (Linux) 中获取字符串 (UTF-8) 的 Unicode

c++ - 创建作为抽象类型对象传递的对象

c++ - LTO for clang 可以跨 C 和 C++ 方法优化吗

c++ - 为什么 clang 仍然需要 libgcc.a 来编译我的代码?

c++ - 将 unsigned int + 字符串转换为 unsigned char vector

c++ auto 多选

在 OSX Sierra 上找不到 C++ header