Minimal example:
#include <iostream>
struct my_class
{
int i;
my_class() : i(0) { std::cout << "default" << std::endl; }
my_class(const my_class&) { std::cout << "copy" << std::endl; }
my_class(my_class&& other) { std::cout << "move" << std::endl; }
my_class(const my_class&& other) { std::cout << "move" << std::endl; }
};
my_class get(int c)
{
my_class m1;
my_class m2;
return (c == 1) ? m1 : m2; // A
//return (c == 1) ? std::move(m1) : m2; // B
//return (c == 1) ? m1 : std::move(m2); // C
}
int main()
{
bool c;
std::cin >> c;
my_class m = get(c);
std::cout << m.i << std::endl; // nvm about undefinedness
return 0;
}
Compiled:
g++ -std=c++11 -Wall -O3 ctor.cpp -o ctor # g++ v 4.7.1
Input:
1
Output:
default
default
copy
-1220217339
This is the In/Output with line A or line C. If I use line B, instead, I get std::move
for some strange reason. In all versions, the output does not depend on my input (except for the value of i).
My questions:
- Why do versions B and C differ?
- Why, at all, does the compiler make a copy in cases A and C?