构造函数中的C ++引用 [英] C++ reference in constructor

查看:136
本文介绍了构造函数中的C ++引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类的构造函数接受一个常量引用一个字符串。这个字符串充当对象的名称,因此在类的一个实例的整个生命周期都是需要的。

I have a class whose constructor takes a const reference to a string. This string acts as the name of the object and therefore is needed throughout the lifetime of an instance of the class.

现在想象一下如何使用这个类:

Now imagine how one could use this class:

class myclass {
public:
    myclass(const std::string& _name) : name(_name) {}
private:
    std::string name;
};

myclass* proc() {
    std::string str("hello");
    myclass* instance = new myclass(str);
    //...
    return instance;
}

int main() {
    myclass* inst = proc();
    //...
    delete inst;
    return 0;
}

由于proc()中的字符串是在堆栈上创建的,因此被删除当proc()完成时,
什么发生在我的类实例中引用它?我的猜想是它变得无效。我会更好地在课堂上保留一份副本吗?我只是想避免任何不必要的复制潜在的大对象,如字符串...

As the string in proc() is created on the stack and therefore is deleted when proc() finishes, what happens with my reference to it inside the class instance? My guess is that it becomes invalid. Would I be better off to keep a copy inside the class? I just want to avoid any unneccessary copying of potentially big objects like a string...

推荐答案

案件。因为你使用字符串,最好保留 myclass 类中的字符串对象的副本。

Yes, Reference becomes invalid in your case. Since you are using the string it is better to keep a copy of the string object in myclass class.

这篇关于构造函数中的C ++引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆