4

I have written a test class to but i'm failing to understanding whats happening!.

Is the Move/copy being elided? if so how could it be updated with the new value. i'm definitely missing something.

here is the test case(Please dont consider the usefulness)

#include<iostream>

struct Test
{
    int a;  
    Test(){a = 10;std::cout<<"def\n";}
    Test(int a){this->a = a;std::cout<<"unary\n";}
    Test(const Test& a){this->a = a.a; std::cout<<"copy\n";}
    Test(Test&& a){this->a = a.a; std::cout<<"Move\n";}
    Test& operator=(const Test& a){this->a = a.a;std::cout<<"op=\n";}
    Test& operator=(Test&& a){this->a = a.a;std::cout<<"Move=\n";}
    void display(){std::cout << "Display ";}
};   


Test gi(Test a)
{
    std::cout<<a.a<<"&\n";
    return a;
}

int main()
{
    //Test a = 99;
    //Test();
/*Line MST*/    Test b = Test(102);//gi(a);  
    std::cout<<b.a<<'\n';

return 0;
}

here line MST is what i dont understand. if i initialize it with a temporary Test object should it not call Move constructor(or atleast the copy)?

the output is :

unary
102

similar output with this line

 Test b = gi(Test(103));

here Move/copy is not happening during call to gi()?

but this is as i expect

Test a = 99;
Test b = gi(a);

what am i missing here?

4

1 回答 1

3

是否删除了移动/复制?如果是这样,如何用新值更新它

是的,根据 C++11 标准的第 12.8/31 节省略了副本。何时以及是否执行此优化完全取决于编译器,您不应该期望它是否正在执行(即使复制构造函数或移动构造函数有副作用)。

于 2013-05-13T12:40:21.630 回答