Skip to content

Commit

Permalink
rule-of-two-soft: Honour explicitly defaulted copy-ctor/operator
Browse files Browse the repository at this point in the history
The user signaled he knows what he's doing and there's even valid
use cases

BUG: 443343
  • Loading branch information
Sergio Martins committed Oct 26, 2021
1 parent 2ea8718 commit 854f340
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/checks/level1/rule-of-two-soft.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ void RuleOfTwoSoft::VisitStmt(Stmt *s)
if (method && method->getParent() && method->isCopyAssignmentOperator()) {
CXXRecordDecl *record = method->getParent();
const bool hasCopyCtor = record->hasNonTrivialCopyConstructor();
const bool hasCopyAssignOp = record->hasNonTrivialCopyAssignment();
const bool hasCopyAssignOp = record->hasNonTrivialCopyAssignment()
|| method->isExplicitlyDefaulted();

if (hasCopyCtor && !hasCopyAssignOp && !isBlacklisted(record)) {
string msg = "Using assign operator but class " + record->getQualifiedNameAsString() + " has copy-ctor but no assign operator";
emitWarning(clazy::getLocStart(s), msg);
Expand All @@ -58,7 +60,8 @@ void RuleOfTwoSoft::VisitStmt(Stmt *s)
CXXConstructorDecl *ctorDecl = ctorExpr->getConstructor();
CXXRecordDecl *record = ctorDecl->getParent();
if (ctorDecl->isCopyConstructor() && record) {
const bool hasCopyCtor = record->hasNonTrivialCopyConstructor();
const bool hasCopyCtor = record->hasNonTrivialCopyConstructor()
|| ctorDecl->isExplicitlyDefaulted();
const bool hasCopyAssignOp = record->hasNonTrivialCopyAssignment();
if (!hasCopyCtor && hasCopyAssignOp && !isBlacklisted(record)) {
string msg = "Using copy-ctor but class " + record->getQualifiedNameAsString() + " has a trivial copy-ctor but non trivial assign operator";
Expand Down
30 changes: 30 additions & 0 deletions tests/rule-of-two-soft/bug443343.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
struct Test
{
Test() {}
~Test() { }

Test(const Test &) {}
Test& operator=(const Test&) = default;
};

void test()
{
Test t;
Test t2;
t = t2; // OK, the developer explicitly says he wants the default copy-assign op
}

struct Test2
{
Test2() {}
~Test2() { }

Test2(const Test2 &) {}
};

void test2()
{
Test2 t;
Test2 t2;
t = t2; // Warn
}
1 change: 1 addition & 0 deletions tests/rule-of-two-soft/bug443343.cpp.expected
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rule-of-two-soft/bug443343.cpp:29:5: warning: Using assign operator but class Test2 has copy-ctor but no assign operator [-Wclazy-rule-of-two-soft]
3 changes: 3 additions & 0 deletions tests/rule-of-two-soft/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
},
{
"filename" : "bug375537.cpp"
},
{
"filename" : "bug443343.cpp"
}
]
}

0 comments on commit 854f340

Please sign in to comment.