相关疑难解决方法(0)

未命名对象上的RVO(返回值优化)是否是普遍保证的行为?

这个问题在不同的方面(也限于gcc)。我的问题仅适用于未命名的对象返回值优化 允许更改结果程序可观察行为。这似乎也在标准中提到。

但是,此“允许”一词令人困惑。这是否意味着RVO 一定会在每个编译器上发生。由于下面的代码更改了RVO,因此可观察到的行为:

#include<iostream>
int global = 0;
struct A {
  A(int *p) {}
  A(const A &obj) { ++ global; }
};

A foo () {  return A(0); }  // <--- RVO happens
int main () {
  A obj = foo(); 
  std::cout<<"global = "<<global<<"\n"; // prints 0 instead of 2
}
Run Code Online (Sandbox Code Playgroud)

global = 0不管编译器优化和方法大小如何,该程序是否都应打印所有实现foo

c++ standards pass-by-value return-value-optimization

5
推荐指数
1
解决办法
938
查看次数

带有可变参数通用引用和复制构造函数的c ++ 11构造函数

如果我们有带有通用引用参数的构造函数,如何声明复制构造函数呢?

http://coliru.stacked-crooked.com/a/4e0355d60297db57

struct Record{
    template<class ...Refs>
    explicit Record(Refs&&... refs){
        cout << "param ctr" << endl;
    }

    Record(const Record& other){     // never called
        cout << "copy ctr" << endl;
    }

    Record(Record&& other){         // never called
        cout << "move ctr" << endl;
    }    
};

int main() {
    Record rec("Hello");    
    Record rec2(rec);  // do "param ctr"

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

根据std::tuple http://en.cppreference.com/w/cpp/utility/tuple/tuple [查看案例3和8]的构造函数列表,这个问题在标准库中以某种方式解决了......但我无法通过stl的码.


PS问题与构造函数中的C++通用引用和返回值优化(rvo)有些相关

PPS目前,我刚Record(call_constructor, Refs&&... refs)为真正的EXPLICIT调用添加了额外的第一个参数.而且我可以手动检测我们是否只有一个参数,如果是Record,并且重定向调用复制ctr/param ctr,但....我不敢相信没有标准的方法...

c++ templates constructor c++11 c++14

5
推荐指数
1
解决办法
764
查看次数