atk*_*ins 14 c++ constructor temporary language-lawyer
在下面的代码中,pS并s.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,但是我对标准不够熟悉,以至于能够确保这是有保证的.
Bar*_*rry 16
没有
编译器没有义务进行复制省略.标准只是指定,[class.copy]:
当满足某些条件时,允许实现省略类对象的复制/移动构造[...]
我可以通过禁用复制省略-fno-elide-constructors,然后两个指针肯定会有所不同.例如:
$g++ -std=c++11 -Wall -pedantic -fno-elide-constructors -Wall -Wextra main.cpp && ./a.out
0x7fff5a598920 0x7fff5a598930
在一般情况下,如果我们添加S(S&& ) = delete,那么上面的代码甚至不会编译.
无法保证不会有临时性.但三巨头编译器将优化它(即使使用-O0开关).
为了保证没有临时性,只需写:
int main()
{
  // ...
  S s{};
  // ...
}
或者干脆S s;.
| 归档时间: | 
 | 
| 查看次数: | 879 次 | 
| 最近记录: |