gpt4 book ai didi

c++ - 在 S s = S() 中是否保证不会创建临时文件?

转载 作者:IT老高 更新时间:2023-10-28 22:33:38 27 4
gpt4 key购买 nike

在下面的代码中,pSs.pS 在最后一行是否保证相等?也就是说,在语句S s = S();中,是否可以确定不会构造一个临时的S

#include <iostream>
using namespace std;

struct S
{
S() { pS = this; }
S* pS;
};

int main()
{
S s = S();
S* pS = &s;
cout << pS << " " << s.pS << endl;
}

在每个编译器中,我都在 pS == s.pS 中对此进行了测试,但我对标准不够熟悉,无法让自己确信这是有保证的。

最佳答案

编译器没有义务进行复制省略。该标准简单地规定,[class.copy]:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object [...]

我可以通过-fno-elide-constructors禁用复制省略,那么这两个指针肯定会不一样。例如:

$g++ -std=c++11 -Wall -pedantic -fno-elide-constructors -Wall -Wextra main.cpp && ./a.out
0x7fff5a598920 0x7fff5a598930

一般情况下,如果我们添加S(S&&) = delete,那么上面的代码甚至不会编译。

关于c++ - 在 S s = S() 中是否保证不会创建临时文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33086346/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com