I compiled this program by g++ and clang++.
G++ executable print one "trigger A copy assignment".
Clang++ executable print two "trigger A copy assignment" and has a segmentation fault.
Does there has any ill-formed? Or is it only clang's problem?
version: gcc-7.4.0/clang-10.0.0
#include <iostream>
struct A {
A &operator =(const A &other) {
std::cout << "trigger A copy assignment\n";
}
};
int main() {
A x,y;
y = x;
}
While not formally ill-formed, your code does create undefined behaviour , as your assignment operator function, declared as returning an A&
, doesn't actually return anything!
From cppreference :
Flowing off the end of a value-returning function (except main) without a return statement is undefined behavior.
This minor code amendment will prevent the clang
crash (but maybe won't do what you want):
struct A {
A& operator =(const A& other) {
std::cout << "trigger A copy assignment\n";
return *this; // MUST return SOMETHING!
}
};
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.