简体   繁体   中英

Copy Elision in visual 2019

I was trying to test a small code to check if my compiler (under Visual Studio 2019) does copy elision, as it is no more optional for some cases under C++17.

So I tried the code below :

#include <iostream>
#include <vector>
using namespace std;

struct myStruct
{
    myStruct() { cout << "default ctor" << endl; }
    myStruct(const myStruct& str) { cout << "copy ctor" << endl; }
    myStruct& operator=(myStruct other) { cout << "Copy assignement" << endl; return *this; }
    myStruct(myStruct&& str) noexcept { cout << "move ctor" << endl; }
    myStruct& operator=(myStruct&& other) { cout << "move assignement" << endl; return *this; }
    ~myStruct() { cout << "deleted" << endl; }
};

myStruct get()
{
    myStruct s;
    return s;
}

int main()
{
    vector<myStruct> vect;
    vect.reserve(10);
    cout << "Creating The Vector" << endl;
    vect.push_back(get());
    vect.push_back(get());
    cout << "Cretion End" << endl;
    return 0;
}

So as far as I read, calling the function get() will trigger the RVO so I will get only ctor calls. But when I run the program I get (I added <<<< in front of lines that are related to copy after calling get() function):

Creating The Vector
default ctor
move ctor
deleted
move ctor  <<<<
deleted    <<<<
default ctor
move ctor
deleted
move ctor  <<<<
deleted    <<<<
Cretion End
deleted
deleted

When tried with gcc I get :

Creating The Vector
default ctor
move ctor
deleted
default ctor
move ctor
deleted
Cretion End
deleted
deleted

So seems that Microsoft still didn't implement the Copy elision, or is there wrong in my code so I missed the real charm of Copy elision?

Thank you in advance

None of the copies in this case are required to be elided by any (currently existing) version of C++. The standard lays down several copies: the copy from s to the return value object of get , and the copy from the reference parameter to push_back into the vector 's internal object. The latter copy cannot be elided, and the former copy's elision is not guaranteed to happen at all.

If you're talking about C++17's guaranteed elision, this only applies to the use of a prvalue to initialize an object (of that type). That never happens here (outside of the temporary parameter passed to call push_back , but that's normal for any version of C++), so it doesn't apply.

Here's a simple test: if the source object of the hypothetical copy has a variable name, then elision if applicable is not mandatory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM