相关疑难解决方法(0)

关于将const引用绑定到临时的子对象

用代码就好

#include <iostream>

struct P {
    int x;
    P(int x) : x(x) {}
    ~P() { std::cout << "~P()\n"; }
};

int main() {
    auto const& x = P{10}.x;
    std::cout << "extract\n";
}
Run Code Online (Sandbox Code Playgroud)

GCC打印~P() extract,表示临时的生命周期未被引用扩展.

相比之下,Clang(IMO正确)将临时的生命周期延长到引用的生命周期,x因此析构函数将在输出后调用main.

请注意,如果我们int使用某种类型(例如string),GCC会突然显示Clang的行为.

这是GCC中的错误还是标准允许的内容?

c++ reference temporary object-lifetime language-lawyer

24
推荐指数
3
解决办法
1203
查看次数

临时数据成员和API设计的终身扩展

假设我有一个跨平台Path类,如:

class Path {
public:
    // ...
    Path parent() const;                // e.g., /foo/bar -> /foo

    std::string const& as_utf8() const {
        return path;
    }
private:
    std::string path;
};
Run Code Online (Sandbox Code Playgroud)

所述parent()成员函数返回的父路径this的路径,所以它(正确)返回一个新构造的Path对象,它表示它.

对于将OS级别的路径表示为UTF-8字符串(例如,Unix)的平台,将as_utf8()引用直接返回到内部表示似乎是合理的,path因为它已经是 UTF-8.

如果我有以下代码:

std::string const &s = my_path.as_utf8();  // OK (as long as my_path exists)
// ...
Path const &parent = my_path.parent();     // OK (temporary lifetime extended)
Run Code Online (Sandbox Code Playgroud)

这两行都很好,因为:

  • 假设my_path持续存在,那么s仍然有效.
  • 返回的临时对象的生命周期parent()由const&.

到现在为止还挺好.但是,如果我有以下代码: …

c++ api-design temporary data-members

8
推荐指数
1
解决办法
112
查看次数