Skip to content

Commit 7950e04

Browse files
committed
Fix: DepthCounter assignment operator/copy constructor
1 parent 7c14384 commit 7950e04

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

PythonScript.Tests/tests/TestDepthCounter.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,23 @@ TEST_F(DepthCounterTest, testMultipleDepth) {
7272
EXPECT_EQ(outsideBlock1, 0);
7373
}
7474

75+
76+
TEST_F(DepthCounterTest, testAssignment) {
77+
DepthCounter depthCounter;
78+
int insideBlock, outsideBlock;
79+
80+
// As the DepthLevel is declared outside the block, we should have the same depth inside and outside the block.
81+
82+
DepthLevel depthLevel;
83+
{
84+
depthLevel = depthCounter.increase();
85+
insideBlock = depthCounter.getDepth();
86+
}
87+
88+
outsideBlock = depthCounter.getDepth();
89+
90+
ASSERT_EQ(insideBlock, 1);
91+
ASSERT_EQ(outsideBlock, 1);
92+
}
93+
7594
}

PythonScript/src/DepthCounter.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,22 @@ DepthLevel::~DepthLevel() {
1010
}
1111
}
1212

13+
DepthLevel& DepthLevel::operator=(const DepthLevel& rhs) {
14+
m_depthCounter = rhs.m_depthCounter;
15+
if (NULL != m_depthCounter) {
16+
m_depthCounter->increaseAsCopy();
17+
}
18+
return *this;
19+
}
20+
21+
22+
DepthLevel::DepthLevel(const DepthLevel& copy)
23+
: m_depthCounter(copy.m_depthCounter)
24+
{
25+
// The copy will also decrement the counter when destroyed, so we need to increase the counter to compensate
26+
if (m_depthCounter) {
27+
m_depthCounter->increaseAsCopy();
28+
}
29+
}
30+
1331
}

PythonScript/src/DepthCounter.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,14 @@ namespace NppPythonScript
1313
{}
1414

1515
~DepthLevel();
16+
17+
DepthLevel& operator=(const DepthLevel& rhs);
18+
DepthLevel(const DepthLevel& copy);
19+
1620

1721
private:
1822
DepthCounter* m_depthCounter;
23+
1924

2025
DepthLevel(DepthCounter* depthCounter)
2126
: m_depthCounter(depthCounter)
@@ -36,6 +41,10 @@ namespace NppPythonScript
3641
int getDepth() { return m_depth; }
3742

3843
protected:
44+
void increaseAsCopy() {
45+
++m_depth;
46+
}
47+
3948
void decrease() {
4049
--m_depth;
4150
}

0 commit comments

Comments
 (0)