Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c++;函数的简单分配 我试图理解C++中如何分配这个配置: Test other = toto();_C++_Allocation - Fatal编程技术网

c++;函数的简单分配 我试图理解C++中如何分配这个配置: Test other = toto();

c++;函数的简单分配 我试图理解C++中如何分配这个配置: Test other = toto();,c++,allocation,C++,Allocation,这是完整的代码源代码: #include <iostream> class Test { public: Test() { j = i++; std::cout<<"default constructor "<<j<<std::endl; } Test(const Test&) { std::cout<<"constuctor by co

这是完整的代码源代码:

#include <iostream>

class Test
{
public:
    Test()
    {
        j = i++;
        std::cout<<"default constructor "<<j<<std::endl;
    }

    Test(const Test&)
    {
        std::cout<<"constuctor by copy "<<j<<std::endl;
    }
    Test & operator=(const Test&)
    {
        std::cout<<"operator = "<<j<<std::endl;
        return *this;
    }
    int j;
    static int i;
};

int Test::i = 0;

Test toto()
{
    Test t;
    return t;
}

int main()
{
    Test other = toto();
    std::cout<<other.j<<std::endl;
    Test another;
    return 0;
}
#包括
课堂测试
{
公众:
测试()
{
j=i++;

std::cout看看哪一种是避免构造函数调用的常见优化方法。

以下格式语义:

Test other = toto();
包含多个副本(但没有赋值)。允许编译器 但是,省略所有不同的实例,这样就消除了 拷贝;几乎所有的编译器都进行这种优化

更具体地说,该标准没有指定类类型的值在何处 返回,但通常的解决方案是由调用方分配 空格,并将指向它的隐藏指针传递到函数中 上述优化:

Test
toto()
{
    Test t;
    return t;
}
将导致构造局部变量
t
,然后 return语句将
t
复制到隐藏 优化(称为命名返回值优化,或 NRVO)这里的结果是编译器使用
t
的隐藏指针,而不是在本地创建单独的
t
。 (显然,当它这样做时,它不会像它那样破坏
t
) 否则,请在复制后执行。)

在宣言中:

Test t = toto();
,形式语义将使编译器为 临时的类型测试,将此空间的地址作为隐藏的 指向
toto
,然后将此临时文件复制到
t
并销毁它。 这里的优化包括编译器传递
t
直接转到
toto
,省去了中间的临时任务。

@jrok-来自常见问题解答“他们的一位工程师告诉我,他们发现这种按值返回的优化速度非常快,即使不在启用优化的情况下编译,也能得到它”所以很明显,这不一定是真的。它可能因编译器而异。@Benj确实,在gcc中尝试过,即使没有优化,也没有副本。