I' playing around with c++14 a bit and I am wondering why my assignment operator is never called. The implementation appears to be correct and I disabled the optimisations (-fno-elide-constructors -O0
) Is this some kind of compiler optimisation I am missing or is something wrong with my code?
#include <iostream>
using namespace std;
int num = 0;
#define LOG_LINE(a) cout << "\n" << (++num) << ".)------------------------> " << #a << "\n"
#define LOG_TEXT cout << "called " << __PRETTY_FUNCTION__ << "\n"
struct Klass {
Klass() { LOG_TEXT; }
~Klass() { LOG_TEXT; }
// copy
Klass(const Klass&) { LOG_TEXT; }
Klass& operator=(const Klass&) { LOG_TEXT; return *this; }
// move
Klass(Klass&&) { LOG_TEXT; }
Klass& operator=(Klass&&) { LOG_TEXT; return *this; }
};
int main() {
LOG_LINE(expecting normal contruction - OK);
auto k1 = Klass{};
auto k12 = Klass();
LOG_LINE(expecting assignment operator - FAIL);
auto k2 = k1;
LOG_LINE(expecting copy construction - OK);
auto k3 = Klass(k2);
LOG_LINE(expecting move assignment - FAIL);
auto k4 = std::move(k3);
LOG_LINE(expecting move construction - OK);
auto k5 = Klass(std::move(k4));
LOG_LINE(expecting destruction of remaining objects - OK);
(void) k5;
return 0;
}
1.)------------------------> expecting normal contruction - OK
called Klass::Klass()
called Klass::Klass(Klass &&)
called Klass::~Klass()
called Klass::Klass()
called Klass::Klass(Klass &&)
called Klass::~Klass()
2.)------------------------> expecting assignment operator - FAIL
called Klass::Klass(const Klass &)
3.)------------------------> expecting copy construction - OK
called Klass::Klass(const Klass &)
called Klass::Klass(Klass &&)
called Klass::~Klass()
4.)------------------------> expecting move assignment - FAIL
called Klass::Klass(Klass &&)
5.)------------------------> expecting move construction - OK
called Klass::Klass(Klass &&)
called Klass::Klass(Klass &&)
called Klass::~Klass()
6.)------------------------> expecting destruction of remaining objects - OK
called Klass::~Klass()
called Klass::~Klass()
called Klass::~Klass()
called Klass::~Klass()
called Klass::~Klass()
called Klass::~Klass()
I am using:
clang ++ --version
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.0.0
Thread model: posix
compiled with:
clang++ source.cpp -std=c++1y -o s -Wpedantic -Wall -Wextra -fno-elide-constructors -O0 && ./s
auto k2 = k1;
is copy initialization, not assignment; it'll call the copy constructor. If you change that line to the following it'll do what you expect
Klass k2; // default construction
k2 = k1; // copy assignment
Similarly
Klass k4; // default construction
k4 = std::move(k3); // move assignment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With