【问题标题】:What happens behind the scenes when initializing a const ref string member with a const char*使用 const char* 初始化 const ref 字符串成员时,幕后会发生什么
【发布时间】:2020-05-15 23:32:25
【问题描述】:

如果 const 字符串是从 const char* 初始化的。我假设创建了一个临时 std::string 对象,并且引用是指临时对象。 对吗?

#include<string>

struct A{
        const std::string& str_;
        A(const std::string& o):str_(o){}
};

int main(){

        A moshe{"moshe"};

}

【问题讨论】:

  • 如果这是一个学术问题,我不确定答案。如果这是我团队的项目,他们会说std::string str_;A(std::string o):str_{std::move(o)} {}
  • 这是我见过的简化版代码。可能不是什么稀奇事,很容易无意间写出这样的代码。

标签: c++


【解决方案1】:

是的,const std::string 将从 const char* 构造,const std::string&amp; 字段将引用这个具有构造函数范围的临时 const std::string

通常,在初始化时,引用会将对象的生命周期延长到它自己的生命周期,但这是一个例外 (cppreference)

每当引用绑定到临时对象或其子对象时,临时对象的生命周期都会延长以匹配引用的生命周期,但以下情况除外:

...

绑定到构造函数初始化列表中的引用成员的临时绑定仅持续到构造函数退出,而不是只要对象存在。 (注意:从 DR 1696 开始,此类初始化格式不正确)。

所以临时的const std::string 只会在你的struct 被构建时处于有效状态。标准允许的事实似乎是一个已知缺陷 (bottom of this page)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2015-10-09
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多