I made a small addition to the exposed sample code to make use of set_test()
and to prevent optimization of dead code:
#include <iostream>
struct Test {
int a;
constexpr Test (int b): a(b) {};
Test(const Test& a);
};
Test::Test(const Test& t) {
this->a = t.a;
}
constexpr Test set_test(int a) {
return Test(a);
}
int main() {
std::cout << "set_test(1).a: " << set_test(1).a << std::endl;
return 0;
}
This works fine in ideone.
It states to use C++ (gcc 6.3)
.
Hence, I was looking for another online compile where I can choose clang
and found Wandbox.
With clang HEAD 7.0.0
it fails to compile. If I got it right set_test()
tries to use the copy constructor which is not constexpr
.
Thus, I delete
d the copy constructor. Now, it fails in return Test(a);
because it tries to access the deleted copy constructor. Strange...
So, I finally provided a move-constructor
constexpr Test(Test &&test): a(test.a) { }
as replacement for the deleted copy constructor. Now, it compiles and works:
#include <iostream>
struct Test {
int a;
constexpr Test (int b): a(b) {}
Test(const Test& a) = delete;
constexpr Test(Test &&test): a(test.a) { }
};
#if 0
Test::Test(const Test& t) {
this->a = t.a;
}
#endif // 0
constexpr Test set_test(int a) {
return Test(a);
}
int main() {
std::cout << "set_test(1).a: " << set_test(1).a << std::endl;
return 0;
}
Output:
Start
set_test(1).a: 1
0
Finish
Life demo on Wandbox.
Out of curiosity, I modified the sample again to try out if making the copy-constructor a constexpr
would fix as well. It does.
Life demo on Wandbox.