2020-04-09

C++ const& 的坑

Views: 8809 | 1 Comment

我们一般很喜欢把函数的参数定义为 const&, 这样即能传引用减少内存拷贝, 也能限定参数为 const 类型不可修改, 似乎很美好. 但是, 如果把对象的属性传给函数, 而对象又被删除时, 就会出错.

struct C
{
    std::string id;
};

class S
{
    C *c = NULL;

    void f1(){
        c = new C();
        c->id = "a";
        f2(c->id);
    }

    void f2(const std::string &id){
        delete c;
        c = new C();
        c->id = "b";
        printf("deleted %s\n", id.c_str()); // core
    }
};

当然, 理论上是写代码的人的错误. 但是, 这确实是一个大坑. 我相信, 这种 case 在实际中还是有不少的. 函数的编写者可能仅仅把参数当作一个无害的对象, 完全没有意识到, 参数变量是和某个要销毁的对象是绑定的. 但是, 又不能强制规定 string 类型只能传值, 然后期待编译器能优化 string 类.

真是坑.

Related posts:

  1. 百行代码实现一个简单的Zset(SortedSet)
  2. PHP 解码 C 字符串
  3. C/C++ 语言 switch-case 后面的花括号
  4. C# 版的 SimpleXML
  5. LevelDB Seek() 特别慢的场景
Posted by ideawu at 2020-04-09 16:21:10

One Response to "C++ const& 的坑"

Leave a Comment