23

C++ const& 的坑

 3 years ago
source link: http://www.ideawu.net/blog/archives/1113.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

我们一般很喜欢把函数的参数定义为 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 类.

真是坑.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK