Tuesday, 27 August 2013

initializing struct while using auto causes a copy in VS 2013

initializing struct while using auto causes a copy in VS 2013

In the following code the line that creates nested object prints only
"constructor" with gcc, but not with VS 2013:
#include <iostream>
using namespace std;
struct test {
test() { cout << "constructor" << endl; }
test(const test&) { cout << "copy constructor" << endl; }
test(test&&) { cout << "move constructor" << endl; }
~test() { cout << "destructor" << endl; }
};
struct nested {
test t;
// nested() {}
};
auto main() -> int {
// prints "constructor", "copy constructor" and "destructor"
auto n = nested{};
cout << endl;
return 0;
}
So I guess what happening here is that a temporary object gets copied into
n. There is no compiler-generated move constructor, so that's why it's not
a move.
I'd like to know if this is a bug or an acceptable behaviour? And why
adding a default constructor prevents a copy here?

No comments:

Post a Comment