Why is GoogleMock leaking my shared_ptr? - c++

I use GoogleMock/GoogleTest for testing, and I'm seeing some strange behavior when a matcher has a shared_ptr to a mock as a parameter, and EXPECT is called on the same shared_ptr. The offending piece of code:
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
using namespace boost;
using namespace testing;
struct MyParameter
{
virtual ~MyParameter() {}
virtual void myMethod() = 0;
};
struct MyParameterMock : public MyParameter
{
MOCK_METHOD0(myMethod, void());
};
struct MyClass
{
virtual ~MyClass() {}
virtual void myMethod(shared_ptr<MyParameter> p) {}
};
struct MyClassMock : public MyClass
{
MOCK_METHOD1(myMethod, void(shared_ptr<MyParameter>));
};
TEST(LeakTest, GoogleMockLeaksMatchedPointer)
{
shared_ptr<MyClassMock> c = make_shared<MyClassMock>();
shared_ptr<MyParameterMock> p = make_shared<MyParameterMock>();
{
InSequence dummy;
EXPECT_CALL(*c, myMethod(Eq(p)));
EXPECT_CALL(*p, myMethod());
}
c->myMethod(p);
p->myMethod();
}
When this test is run, I get
leak_ptr_mock.cpp:37: ERROR: this mock object (used in test LeakTest.GoogleMockLeaksMatchedPointer) should be deleted but never is. Its address is #0x9309544.
ERROR: 1 leaked mock object found at program exit.
Any idea of why this happens? I rather not have to use Mock::AllowLeak.

This is a result of holding p as a shared_ptr, using InSequence and the order in which you have declared your expectations.
When you call
EXPECT_CALL(*c, myMethod(Eq(p)));
you increase the use_count of p. In order for the leak detection to pass, p must be destroyed at (or before) the end of TEST.
The problem here is that internally, gmock maintains a record of the required mock call sequence by holding a pointer to the preceding expectation. So when you call EXPECT_CALL(*p, myMethod());, it gets a copy of the pointer to the previous expectation.
This then has the effect of blocking the call to p's destructor when TEST ends.
In order to work around this, I think your best bet is to call
EXPECT_TRUE(Mock::VerifyAndClearExpectations(p.get()));
just before you exit TEST. This clears the expectations on p, including critically its prerequisite expectation, which in turn allows the destructor of p to be invoked correctly.
Alternatively, if the order of the mock calls is unimportant, simply removing InSequence dummy; will also allow p's destructor to execute.
As an aside, your code has a couple of issues;
Your base structs should have virtual destructors
MyClass::myMethod should be virtual in order to allow gmock's function to override it
p->myMethod(p); should be p->myMethod();

Related

Google mock with unique_ptr object giving memory leak issue

I am new to Google Test.
I have one base class and derived class with calling class
class Base
{
public:
virtual ~Base() {}
virtual int target_method() = 0;
}
class DerivedClass : public Base
{
public:
virtual ~DerivedClass () {}
int target_method() override;
}
class CallingClass
{
public:
CallingClass(std::unique_ptr<DerivedClass> _drivedClass);
private:
std::unique_ptr<DerivedClass> drivedClass;
}
From my Test:
class MockDerivedClass : public DerivedClass
{
public:
MOCK_METHOD0(target_method, int());
}
TEST(TestGroup, Test1)
{
std::unique_ptr<MockDerivedClass> mockClass(new MockDerivedClass());
EXPECT_CALL(*mockClass, target_method()).WillRepeatedly(Return(1));
CallingClass callingClass(std::move(mockClass));
callingClass.callSomthing();
EXPECT_EQ(_ , _);
}
The test is running fine and the mock method is being called as expected. At the end of test I am getting this error:
ERROR: this mock object (used in test TestGroup.Test1) should be deleted but never is. Its address is #0x5585d93e4770.
ERROR: 1 leaked mock object found at program exit. Expectations on a mock object is verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock.
Is there anything can be done at end of test to suppress this or to resolve this?
By using a uniqe_ptr, the owner of the mock object becomes the CallingClass. The leak detection expects mockClass to be destructed within your TEST, not possibly after that.
Note that gMock will verify the expectations on a mock object when it is destructed. See this reference.
You can either avoid using a unique pointer and construct the mock object in your test and just pass its address to your CallingClass, or add this at the end of your test:
EXPECT_TRUE(Mock::VerifyAndClearExpectations(mockClass.get()));
This verifies and removes the expectations on mockClass and returns true if and only if successful.

Is there any issues with this factory pattern implementation

Recently I asked following question:
Best method to implement an abstract factory pattern
My future research show that you can implement the factory like this:
#include <stdio.h>
#include <memory>
class Base{
char x[20000];
};
class Child : public Base{
public:
Child(int a, int b){
}
};
std::unique_ptr<Base> factory(){
return std::unique_ptr<Base> { new Child(5, 6) };
}
int main(){
Base & a = *factory();
return 0;
}
This compiles without warnings, and it make no memory leak, even std::unique_ptr is dereferenced immediately.
Is this Base & a = *factory(); legitimate and well accepted way to "collect" value from factory?
The only problem I see here would be if a variable leave the scope. Is there something I am missing here?
Base &a = *factory();
You dereferenced the unique_ptr and kept the reference to its pointee.
But you didn't store the unique_ptr itself.
Thus it dies at the end of the statement, taking its pointee with it, and your reference is now dangling.

Problems with C++ abstract class (I can do it in Java, but not in C++!)

First of all, I searched this problem and found a lot of similiar questions, but I couldn't find an answer that fixed my problem. I am very sorry if that is just me being dumb.
What I am trying to do is make the constructor of an abstract class call a function that is pure virtual. In Java, this works, because the subclass provides the implementation of the abstract method that is called. However, in C++, I get this linker error:
test.o:test.cpp:(.text$_ZN15MyAbstractClassC2Ev[MyAbstractClass::MyAbstractClass
()]+0x16): undefined reference to `MyAbstractClass::initialize()'
collect2: ld returned 1 exit status
Here is my code:
#include <iostream>
class MyAbstractClass {
protected:
virtual void initialize() = 0;
public:
MyAbstractClass() {
initialize();
}
};
class MyClass : public MyAbstractClass {
private:
void initialize() {
std::cout << "yey!" << std::endl;
}
};
int main() {
MyClass *my = new MyClass();
return 0;
}
As a further explanation of what I am trying to do, here is code in Java that achieves my goal:
public abstract class MyAbstractClass {
public MyAbstractClass() {
initialize();
}
protected abstract void initialize();
}
public class MyClass extends MyAbstractClass {
protected void initialize() {
System.out.println("Yey!");
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
}
}
This code prints "Yey!". Any help much appreciated!
MyAbstractClass() {
initialize();
}
That will not perform a virtual dispatch to MyClass::initialize(), because at this stage of the object's construction its MyClass parts haven't been created yet. Thus you really are invoking MyAbstractClass::initialize() and, as such, it must be defined. (Yes, pure virtual member functions can be defined.)
Try to avoid invoking virtual member functions from constructors, because this sort of stuff will happen and catch you out. It rarely makes sense to do it.
Also, try to avoid initialize() functions; you already have constructors to play with.
Update
Actually, though you may take the above as read for any other virtual member function, invoking a pure virtual member function from the constructor yields Undefined Behaviour. So don't even try!
In C++, you can't call a pure virtual function from a constructor or destructor (even if it has a definition). If you call a non-pure one, then it will be dispatched as if the object's type were the class under construction, so you'll never be able to call a function defined in a derived class.
In this case, you don't need to; the derived class's constructor will be called after the base class's, so you get the desired result from:
#include <iostream>
class MyAbstractClass {
public:
MyAbstractClass() {
// don't do anything special to initialise the derived class
}
};
class MyClass : public MyAbstractClass {
public:
MyClass() {
std::cout << "yey!" << std::endl;
}
};
int main() {
MyClass my;
return 0;
}
Note that I also changed my to an automatic variable; you should get in the habit of using them whenever you don't need dynamic allocation, and learn how to use RAII to manage dynamic resources when you really do need them.
Let me quote Scott Meyers here (see Never Call Virtual Functions during Construction or Destruction):
Item 9: Never call virtual functions during construction or destruction.
I'll begin with the recap: you shouldn't call virtual functions during construction or destruction, because the calls won't do what you think, and if they did, you'd still be unhappy. If you're a recovering Java or C# programmer, pay close attention to this Item, because this is a place where those languages zig, while C++ zags.
The issue: during object construction the virtual function table might not yet be ready. Just imagine that your class is eg. fourth in line of inheritance. Constructors are called in inheritance order, so while calling this pure virtual (or even if it was non-pure) you would like the base class to call initialize for an object that is not yet complete!
The C++ side has been handled in other answers, but I want to add a remark on the Java side of it. Calling a virtual function from a constructor is a problem in all cases, not just in C++. Basically what the code is trying to do is execute a method on an object that has not yet been created and that is an error.
The two solutions implemented in the different languages differ in trying to make some sense of what your code is trying to do. In C++ the decision is that during construction of a base object, and until construction of the derived object starts, the actual type of the object is base, which means that there won't be dynamic dispatch. That is, the type of the object at any time is that of the constructor being executed[*]. While this is surprising to some (you among others), it provides a sensible solution to the problem.
[*] Conversely the destructor. The type also changes as the most derived constructors complete.
The alternative in Java is that the object is of the final type from the beginning, even before construction has completed. In Java, as you demonstrated, the call will be dispatched to the final overrider (I am using C++ slang here: to the last implementation of the virtual function in the execution chain), and that can cause unwanted behavior. Consider for example this implementation of initialize():
public class MyClass extends MyAbstractClass {
final int k1 = 1;
final int k2;
MyClass() {
k2 = 2;
}
void initialize() {
System.out.println( "Constant 1 is " + k1 + " and constant 2 is " + k2 );
}
}
What is the output of the previous program? (Answer at the bottom)
More than just a toy example, consider that MyClass provides some invariants that are set at construction time and hold for the whole lifetime of the object. Maybe it holds a reference to a logger on which data can be dumped. By looking at the class, you can see that the logger is set in the constructor and assume that it cannot be reset anywhere in the code:
public class MyClass extends MyAbstractClass {
Logger logger;
MyClass() {
logger = new Logger( System.out );
}
void initialize() {
logger.debug( "Starting initialization" );
}
}
You probably see now where this is going. By looking at the implementation of MyClass there does not seem to be anything wrong at all. logger is set in the constructor, so it can be used in all methods of the class. Now the problem is that if MyAbstractClass calls on a virtual function that gets dispatched then the application will crash with a NullPointerException.
By now I hope that you understand and value the C++ decision of not performing dynamic dispatch and thus avoid executing functions on objects that have not yet been fully initialized (or conversely have already been destroyed, if the virtual call is in the destructor).
(Answer: this might depend on the compiler/JVM, but when I tried this long long time ago, the line printed Constant 1 is 1 and constant 2 is 0. If you are happy with that, fine by me, but I found that to be surprising... The reason for the 1/0 in that compiler is that the process of initialization first sets the values that are in the variable definition, and then calls the constructors. This means that the first step of construction would set k1 before calling MyAbstractBase constructor, that would call initialize() before MyBase constructor has run and set the value of the second constant).
During construction and destruction, the virtual table is set up appropriately for the base subobject being constructed or destroyed. This is the theoretically correct thing to do, because the more-derived class is not alive (its lifetime either hasn't yet started or has already ended).
As already explained by #Seth, you cannot call virtual functions in a constructor. More specifically, the virtual dispatch mechanism is disabled during construction and destruction. Either make your initialize member function nonvirtual and implement it in the base class, or have the user call it explicitly.

Critique this c++ code

Similar to the code written below exists in production. Could you people review it and tell me if such code works well all the time.
class Base
{
public:
virtual void process() = 0;
};
class ProductA : public Base
{
public:
void process()
{
// some implementation.
doSomething();
}
void setSomething(int x)
{
}
virtual void doSomething()
{
// doSomething.
}
};
class ProductANew : public ProductA
{
public:
ProductANew() : ProductA() { }
void doSomething()
{
// do Something.
}
};
int main(int argc, char *argv[])
{
Base* bp = new ProductANew();
dynamic_cast<ProductA*>(bp)->setSomething(10);
bp->process();
}
Some problems:
the base class must have a virtual destructor
you never delete the object allocated with new
you never test the result of dynamic_cast
With good design you wouldn't need a dynamic_cast. If process() can't be called without calling setSomething() first they should have been exposed in the same base class.
There's one actual error and a bunch of dangerous/questionable practices:
The one error is that you never call delete on your newed object, so it leaks.
Questionable practices:
Base doesn't have a virtual destructor, so if you correct the error by calling delete or using an auto_ptr, you'll invoke undefined behaviour.
There's no need to use dynamic allocation here at all.
Polymorphic base classes should be uncopyable to prevent object slicing.
You're using a dynamic_cast where it's not neccessary and without checking the result - why not just declare bp as a pointer to ProductANew or ProductNew?
ProductANew doesn't need a constructor - the default one will do just fine.
A few of these points may be a result of the nature of your example - i.e. you have good reason to use dynamic allocation, but you wanted to keep your example small.
Generally you'll find that code which can't even compile is badly designed.
Base* bp = new ProductANew();
This line can't work because ProductANew isn't inherited from Base in any way, shape or form.
$ gcc junk.cc
junk.cc: In function ‘int main(int, char**)’:
junk.cc:41: error: cannot convert ‘ProductANew*’ to ‘Base*’ in initialization
(Just to be clear: junk.cc contains your code cut and pasted.)
Edited to add...
Latecomers may want to look at the history of the original question before down-voting. ;)

Trouble understanding C++ `virtual`

I'm having trouble understanding what the purpose of the virtual keyword in C++. I know C and Java very well but I'm new to C++
From wikipedia
In object-oriented programming, a
virtual function or virtual method is
a function or method whose behavior
can be overridden within an inheriting
class by a function with the same
signature.
However I can override a method as seen below without using the virtual keyword
#include <iostream>
using namespace std;
class A {
public:
int a();
};
int A::a() {
return 1;
}
class B : A {
public:
int a();
};
int B::a() {
return 2;
}
int main() {
B b;
cout << b.a() << endl;
return 0;
}
//output: 2
As you can see below, the function A::a is successfully overridden with B::a without requiring virtual
Compounding my confusion is this statement about virtual destructors, also from wikipedia
as illustrated in the following example,
it is important for a C++ base class
to have a virtual destructor to ensure
that the destructor from the most
derived class will always be called.
So virtual also tells the compiler to call up the parent's destructors? This seems to be very different from my original understanding of virtual as "make the function overridable"
Make the following changes and you will see why:
#include <iostream>
using namespace std;
class A {
public:
int a();
};
int A::a() {
return 1;
}
class B : public A { // Notice public added here
public:
int a();
};
int B::a() {
return 2;
}
int main() {
A* b = new B(); // Notice we are using a base class pointer here
cout << b->a() << endl; // This will print 1 instead of 2
delete b; // Added delete to free b
return 0;
}
Now, to make it work like you intended:
#include <iostream>
using namespace std;
class A {
public:
virtual int a(); // Notice virtual added here
};
int A::a() {
return 1;
}
class B : public A { // Notice public added here
public:
virtual int a(); // Notice virtual added here, but not necessary in C++
};
int B::a() {
return 2;
}
int main() {
A* b = new B(); // Notice we are using a base class pointer here
cout << b->a() << endl; // This will print 2 as intended
delete b; // Added delete to free b
return 0;
}
The note that you've included about virtual destructors is exactly right. In your sample there is nothing that needs to be cleaned-up, but say that both A and B had destructors. If they aren't marked virtual, which one is going to get called with the base class pointer? Hint: It will work exactly the same as the a() method did when it was not marked virtual.
You could think of it as follows.
All functions in Java are virtual. If you have a class with a function, and you override that function in a derived class, it will be called, no matter the declared type of the variable you use to call it.
In C++, on the other hand, it won't necessarily be called.
If you have a base class Base and a derived class Derived, and they both have a non-virtual function in them named 'foo', then
Base * base;
Derived *derived;
base->foo(); // calls Base::foo
derived->foo(); // calls Derived::foo
If foo is virtual, then both call Derived::foo.
virtual means that the actual method is determined runtime based on what class was instantiated not what type you used to declare your variable.
In your case this is a static override it will go for the method defined for class B no matter what was the actual type of the object created
So virtual also tells the compiler to call up the parent's destructors? This seems to be very different from my original understanding of virtual as "make the function overridable"
Your original and your new understanding are both wrong.
Methods (you call them functions) are always overridable. No matter if virtual, pure, nonvirtual or something.
Parent destructors are always called. As are the constructors.
"Virtual" does only make a difference if you call a method trough a pointer of type pointer-to-baseclass. Since in your example you don't use pointers at all, virtual doesn't make a difference at all.
If you use a variable a of type pointer-to-A, that is A* a;, you can not only assign other variables of type pointer-to-A to it, but also variables of type pointer-to-B, because B is derived from A.
A* a;
B* b;
b = new B(); // create a object of type B.
a = b; // this is valid code. a has still the type pointer-to-A,
// but the value it holds is b, a pointer to a B object.
a.a(); // now here is the difference. If a() is non-virtual, A::a()
// will be called, because a is of type pointer-to-A.
// Whether the object it points to is of type A, B or
// something entirely different doesn't matter, what gets called
// is determined during compile time from the type of a.
a.a(); // now if a() is virtual, B::a() will be called, the compiler
// looks during runtime at the value of a, sees that it points
// to a B object and uses B::a(). What gets called is determined
// from the type of the __value__ of a.
As you can see below, the function A::a is successfully overridden with B::a without requiring virtual
It may, or it may not work. In your example it works, but it's because you create and use an B object directly, and not through pointer to A. See C++ FAQ Lite, 20.3.
So virtual also tells the compiler to call up the parent's destructors?
A virtual destructor is needed if you delete a pointer of base class pointing to an object of derived class, and expect both base and derived destructors to run. See C++ FAQ Lite, 20.7.
You need the virtual if you use a base class pointer as consultutah (and others while I'm typing ;) ) says it.
The lack of virtuals allows to save a check to know wich method it need to call (the one of the base class or of some derived). However, at this point don't worry about performances, just on correct behaviour.
The virtual destructor is particulary important because derived classes might declare other variables on the heap (i.e. using the keyword 'new') and you need to be able to delete it.
However, you might notice, that in C++, you tend to use less deriving than in java for example (you often use templates for a similar use), and maybe you don't even need to bother about that. Also, if you never declare your objects on the heap ("A a;" instead of "A * a = new A();") then you don't need to worry about it either. Of course, this will heavily depend on what/how you develop and if you plan that someone else will derive your class or not.
Try ((A*)&b).a() and see what gets called then.
The virtual keyword lets you treat an object in an abstract way (I.E. through a base class pointer) and yet still call descendant code...
Put another way, the virtual keyword "lets old code call new code". You may have written code to operate on A's, but through virtual functions, that code can call B's newer a().
Say you instantiated B but held it as an instance of an A:
A *a = new B();
and called function a() whose implementation of a() will be called?
If a() isn't virtual A's will be called. If a() was virtual the instantiated sub class version of a() would be called regardless of how you're holding it.
If B's constructor allocated tons of memory for arrays or opened files, calling
delete a;
would ensure B's destructor was called regardless as to how it was being held, be it by a base class or interface or whatever.
Good question by the way.
I always think about it like chess pieces (my first experiment with OO).
A chessboard holds pointers to all the pieces. Empty squares are NULL pointers. But all it knows is that each pointer points a a chess piece. The board does not need to know more information. But when a piece is moved the board does not know it is a valid move as each pice has different characteristica about how it moves. So the board needs to check with the piece if the move is valid.
Piece* board[8][8];
CheckMove(Point const& from,Point const& too)
{
Piece* piece = board[from.x][from.y];
if (piece != NULL)
{
if (!piece->checkValidMove(from,too))
{ throw std::exception("Bad Move");
}
// Other checks.
}
}
class Piece
{
virtual bool checkValidMove(Point const& from,Point const& too) = 0;
};
class Queen: public Piece
{
virtual bool checkValidMove(Point const& from,Point const& too)
{
if (CheckHorizontalMove(from,too) || CheckVerticalMoce(from,too) || CheckDiagonalMove(from,too))
{
.....
}
}
}