Background: The C++ interface of IBM ILOG Cplex allocates and de-allocates memory rather unconventionally:
A declaration of an ILO environment IloEnv environment;, followed by a construction of models and solvers within this environment, followed by all these objects (including the environment) going out of scope results in a memory leak. Note that I have not used the new operator. One way to avoid this is to call environment.end(); before the object goes out of scope.
Setting: Now, I have a class whose purpose is to solve a specific ILP. This class has some member variables:
IloEnv ilpEnvironment_;
IloObjective ilpObjective_;
IloExpr ilpExpression_;
IloModel ilpModel_;
IloCplex ilpSolver_;
IloNumArray ilpSolution_;
IloNumVarArray ilpVariables_;
IloNumArray ilpStartValues_;
IloRangeArray constraints_;
These member variables are initialized in the initializer list of the constructor:
inline MyClass::MyClass()
: ilpEnvironment_(),
ilpObjective_(ilpEnvironment_),
ilpExpression_(ilpEnvironment_),
ilpModel_(ilpEnvironment_),
ilpSolver_(ilpModel_),
ilpSolution_(ilpEnvironment_),
ilpVariables_(ilpEnvironment_),
ilpStartValues_(ilpEnvironment_),
constraints_(ilpEnvironment_)
{ /* ... */ }
The destructor de-allocates all the memory (that has been allocated by member functions of the class that operate on the member variables):
inline MyClass::~MyClass() {
ilpEnvironment_.end();
}
Question: How do i implement a member function void clear() that de-allocates the memory and puts the class back into its initial state? Here are two rather naive attempts I made that don't work:
inline void MyClass::clear() {
ilpEnvironment_.end();
ilpEnvironment_ = IloEnv(); // does not work, whether or not I comment this line out
ilpObjective_ = IloObjective(ilpEnvironment_);
ilpExpression_ = IloExpr(ilpEnvironment_);
ilpModel_ = IloModel(ilpEnvironment_);
ilpSolver_ = IloCplex(ilpEnvironment_);
ilpSolution_ = IloNumArray(ilpEnvironment_);
ilpVariables_ = IloNumVarArray(ilpEnvironment_);
ilpStartValues_ = IloNumArray(ilpEnvironment_);
constraints_ = IloRangeArray(ilpEnvironment_);
}
If the purpose of the class is to solve a specific ILP model, then I would initialize the class with the model size/parameters, and create and destroy the CPLEX objects within a solve() member function while saving only the results as class members. Class members would be model parameters, and the object would keep all CPLEX dealings hidden.
You could even have a class member that keeps track of which constraints to activate in that particular solve() call.
If you absolutely have to use the CPLEX objects as changeable class members, then you might want to try to use object pointers as class members instead of the objects themselves. Calling IloEnv::end() destroys the objects associated with it, so you could call IloEnd::end() and then reassign the pointers to new objects.
Related
I frequently come across a situation where we create a class that acts on some enumeration, but later we derive and we want to add more values to the enumeration without changing the base class.
I see this question from 2009:
Base enum class inheritance
However, I know there were a number of changes to enum in C++11, 14, 17.
Do any of those changes allow for extension of enums from base class to derived?
class Base
{
enum State {STATE_1, STATE_2, STATE_3};
};
class Derived : public Base
{
enum State {STATE_4};
};
...where we want derived to have an enumeration describing the states it can be in, which are: STATE_1, STATE_2, STATE_3, and STATE_4. We don't really want to change the enumeration in the base class, because other derived classes might not have the ability to be in STATE_4. We don't really want to create a new enumeration either, because we already have one for State in the Base.
Do we still use static const values instead in order to accomplish this 8 years later?
class Base
{
static int STATE_1= 0;
static int STATE_2= 1;
static int STATE_3= 2;
};
class Derived : public Base
{
static int STATE_4= 3;
};
No, C++ does not allow this sort of thing. Base::Color is a completely separate type from Derived::Color, with zero connection to them. This is no different from any other nested types; nested types defined in a base class are not connected to nested types defined in a derived class.
Nor can enumerations be inherited from one another.
This sort of things tends to go against good OOP practices anyway. After all, if a derived class introduces a new enumerator, how would the base class handle it? How would different derived class instances handle it?
If Base defines an operation over an enumeration, then Base defines the totality of the enumeration it operates on, and every class derived from it ought to be able to handle all of those options. Otherwise, something is very wrong with your virtual interface.
Why not just using namespaces to group enums?
namespace my_codes {
enum class color { red, green, blue } ;
enum class origin { server, client } ;
} // my_codes
Usage might be
struct my_signal {
my_codes::color flag ;
my_codes::origin source ;
} ;
But beware: "overkill is my biggest fear..." :) I would not enjoy some deep hierarchy of namespaces with enums in them and a such ...
With the struct definition given below...
struct A {
virtual void hello() = 0;
};
Approach #1:
struct B : public A {
virtual void hello() { ... }
};
Approach #2:
struct B : public A {
void hello() { ... }
};
Is there any difference between these two ways to override the hello function?
They are exactly the same. There is no difference between them other than that the first approach requires more typing and is potentially clearer.
The 'virtualness' of a function is propagated implicitly, however at least one compiler I use will generate a warning if the virtual keyword is not used explicitly, so you may want to use it if only to keep the compiler quiet.
From a purely stylistic point-of-view, including the virtual keyword clearly 'advertises' the fact to the user that the function is virtual. This will be important to anyone further sub-classing B without having to check A's definition. For deep class hierarchies, this becomes especially important.
The virtual keyword is not necessary in the derived class. Here's the supporting documentation, from the C++ Draft Standard (N3337) (emphasis mine):
10.3 Virtual functions
2 If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (8.3.5), cv-qualification, and ref-qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.
No, the virtual keyword on derived classes' virtual function overrides is not required. But it is worth mentioning a related pitfall: a failure to override a virtual function.
The failure to override occurs if you intend to override a virtual function in a derived class, but make an error in the signature so that it declares a new and different virtual function. This function may be an overload of the base class function, or it might differ in name. Whether or not you use the virtual keyword in the derived class function declaration, the compiler would not be able to tell that you intended to override a function from a base class.
This pitfall is, however, thankfully addressed by the C++11 explicit override language feature, which allows the source code to clearly specify that a member function is intended to override a base class function:
struct Base {
virtual void some_func(float);
};
struct Derived : Base {
virtual void some_func(int) override; // ill-formed - doesn't override a base class method
};
The compiler will issue a compile-time error and the programming error will be immediately obvious (perhaps the function in Derived should have taken a float as the argument).
Refer to WP:C++11.
Adding the "virtual" keyword is good practice as it improves readability , but it is not necessary. Functions declared virtual in the base class, and having the same signature in the derived classes are considered "virtual" by default.
There is no difference for the compiler, when you write the virtual in the derived class or omit it.
But you need to look at the base class to get this information. Therfore I would recommend to add the virtual keyword also in the derived class, if you want to show to the human that this function is virtual.
The virtual keyword should be added to functions of a base class to make them overridable. In your example, struct A is the base class. virtual means nothing for using those functions in a derived class. However, it you want your derived class to also be a base class itself, and you want that function to be overridable, then you would have to put the virtual there.
struct B : public A {
virtual void hello() { ... }
};
struct C : public B {
void hello() { ... }
};
Here C inherits from B, so B is not the base class (it is also a derived class), and C is the derived class.
The inheritance diagram looks like this:
A
^
|
B
^
|
C
So you should put the virtual in front of functions inside of potential base classes which may have children. virtual allows your children to override your functions. There is nothing wrong with putting the virtual in front of functions inside of the derived classes, but it is not required. It is recommended though, because if someone would want to inherit from your derived class, they would not be pleased that the method overriding doesn't work as expected.
So put virtual in front of functions in all classes involved in inheritance, unless you know for sure that the class will not have any children who would need to override the functions of the base class. It is good practice.
There's a considerable difference when you have templates and start taking base class(es) as template parameter(s):
struct None {};
template<typename... Interfaces>
struct B : public Interfaces
{
void hello() { ... }
};
struct A {
virtual void hello() = 0;
};
template<typename... Interfaces>
void t_hello(const B<Interfaces...>& b) // different code generated for each set of interfaces (a vtable-based clever compiler might reduce this to 2); both t_hello and b.hello() might be inlined properly
{
b.hello(); // indirect, non-virtual call
}
void hello(const A& a)
{
a.hello(); // Indirect virtual call, inlining is impossible in general
}
int main()
{
B<None> b; // Ok, no vtable generated, empty base class optimization works, sizeof(b) == 1 usually
B<None>* pb = &b;
B<None>& rb = b;
b.hello(); // direct call
pb->hello(); // pb-relative non-virtual call (1 redirection)
rb->hello(); // non-virtual call (1 redirection unless optimized out)
t_hello(b); // works as expected, one redirection
// hello(b); // compile-time error
B<A> ba; // Ok, vtable generated, sizeof(b) >= sizeof(void*)
B<None>* pba = &ba;
B<None>& rba = ba;
ba.hello(); // still can be a direct call, exact type of ba is deducible
pba->hello(); // pba-relative virtual call (usually 3 redirections)
rba->hello(); // rba-relative virtual call (usually 3 redirections unless optimized out to 2)
//t_hello(b); // compile-time error (unless you add support for const A& in t_hello as well)
hello(ba);
}
The fun part of it is that you can now define interface and non-interface functions later to defining classes. That is useful for interworking interfaces between libraries (don't rely on this as a standard design process of a single library). It costs you nothing to allow this for all of your classes - you might even typedef B to something if you'd like.
Note that, if you do this, you might want to declare copy / move constructors as templates, too: allowing to construct from different interfaces allows you to 'cast' between different B<> types.
It's questionable whether you should add support for const A& in t_hello(). The usual reason for this rewrite is to move away from inheritance-based specialization to template-based one, mostly for performance reasons. If you continue to support the old interface, you can hardly detect (or deter from) old usage.
I will certainly include the Virtual keyword for the child class, because
i. Readability.
ii. This child class my be derived further down, you don't want the constructor of the further derived class to call this virtual function.
I'm currently designing a class structure for a project I'm working on. I have a method that uses one instance state. I don't now wheter it's better to make this method static and parse this instance state as an argument or just tie the method to the instance.
If performance was no issue I would tie the method without any doubt to the instance, because it's much cleaner that way. But in my case performance will be really crucial. So, does it make any difference performance-wise to make the method static / non-static?
If it makes no difference, will that be true for the generated *.dart.js javascript aswell?
Edit:
After reading my own question it's not really coherent. I will try to formulate it again, but clearer.
This code ...
class MyClass {
void foo() {}
}
void main() {
MyClass a = new MyClass();
MyClass b = new MyClass();
print(a.foo == b.foo);
}
... outputs false. This make me think that for each new instance a new method is created. If that is true this seems to me as a waste of memory. So, does each new instance create a copy of all it's bound methods?
PS: The question is basically the same as this question, but then for Dart.
No, creating two instances doesn't duplicate the methods. Methods are like static functions where the object instance is passesd as argument with the name this.
Don't worry too much about performance before you run into actual performance issues especially at such micro-level.
Usually performance isn't a matter for the bigger part of your applications code base because most of the code is usually run very seldom.
When you run into performance issues you can investigate and find the real hot spots that are executed often enough so that optimization actually makes a difference.
Dart classes don't have different methods for different instances.
There is only one method per class.
Extracting a function creates a new function object every time you do it, and those objects may or may not be equal depending on which function you extract from which objects:
class MyClass {
void foo() {}
}
void main() {
MyClass a = new MyClass();
MyClass b = new MyClass();
print(a.foo == b.foo); // False.
print(a.foo == a.foo); // True
print(identical(a.foo, a.foo)); // False!
}
When you perform a method extraction from an object, you create a new object. The new object is a "closure" which contains the function to call and the object to call it on. Two such closures are equal (according to operator==) if they refer to the same function on the same object. That's why a.foo and b.foo are not equal - they are equivalent to () => a.foo() and () => b.foo() respectively, and since a and b are not the same object, the function objects are not considered equal.
While reading up on the new features introduced in Java 8, I came across the concept of Predicates. I noticed that most of the examples provided on the internet and in books use static functions to create predicates.
Consider the following Apple class for example :
public class Apple {
private String color;
private int weight;
private static final int SMALL_APPLE_MAX_WEIGHT = 150;
public Apple(String color, int weight) {
this.color = color;
this.weight = weight;
}
public static boolean isGreenApple(Apple apple) {
return null!=apple && null!=apple.getColor() && "green".equals(apple.getColor());
}
public boolean isBigApple() {
return this.getWeight() > SMALL_APPLE_MAX_WEIGHT;
}
}
I can now create a new predicate as follows :
Predicate<Apple> isGreenApple = Apple::isGreenApple;
Predicate<Apple> isBigApple = Apple::isBigApple;
As shown above, I can create a predicate using both a static as well as an instance method. Which approach is the preferred approach then and why?
For a method reference, there is no difference between an instance method A.foo() and a static method foo(A), in fact, the compiler will reject a method reference as ambiguous if both exist.
So the decision whether to use an instance method or a static method does not depend on the question whether you want to create a function via method reference for it.
Rather, you have to apply the same considerations us usual. Should the method be overridable, it has to be an instance method, otherwise, if it represents a fixed algorithm, you may consider a static method, but of course, a final method would do as well.
static methods are obviously unavoidable when you are not the maintainer of the class whose instance you want to process, in other words, when the containing class has to be different than the class of the instance. But even if the class is the same but you feel that it could be placed in another (utility) class as well, declaring it as static might be the better choice.
This holds especially when there are more than one parameter and the first one isn’t special to the operation, e.g. max(Foo,Foo) should be a static method rather than an instance method max(Foo) on Foo.
But in the end there are different programming styles out there and the answer is that method references do not mandate a particular programming style.
Regarding why there are so many examples using static methods; well I don’t know enough examples to decide whether your observation is right or just a subjective view. But maybe some tutorial writers are themselves not aware about the possibility to refer to an instance method as a function taking the method receiver as first argument.
I think, there are examples, like
Predicate<String> empty=String::isEmpty;
Predicate<CharSequence> isHello="hello"::contentEquals;
which are worth to be shown in tutorials to emphasize that you are not required to create methods specially intended to be used as method references, but that in fact there are a lot of already existing methods, static and non-static, to be directly usable with method references.
What I am more interested in knowing is why are all examples on predicates shown using static methods?
The reference appears on the Class as no additional argument is required.
Any specific reason for not using instance methods?
For non-static methods that would make sense. In the case of
Predicate<Apple> isBigApple = Apple::isBigApple;
Predicate needs a argument so it takes this. An example of a non-method call would be something like
List<Apple> bigApples = new ArrayList<>();
apples.stream().filter(Apple::isBigApple).forEach(bigApple::add);
I want to have a static variable in Cocoa.
After looking at How do I declare class-level properties in Objective-C?, I am unclear whether there is anything wrong with what I have always done so far, i.e.
// Foo.m
static NSString* id;
#interface Foo ()
instead of
// Foo.h
#interface Foo {
}
+(NSString*) id;
// Foo.m
+(NSString*) id
{
static NSString* fooId = nil;
if (fooId == nil)
{
// create id
}
return fooId;
}
Obviously, the second approach offers an opportunity for initializing the id. But if I initialize the id myself somewhere else in the code, within, say a getter:
-(NSString*) getId
{
if (id==nil) {
id = ... // init goes here
}
return id;
}
Then is there anything wrong with the simple static declaration approach as opposed to the more complex class function approach? What am I missing?
First, what you are asking for is a global variable, a static is similar but a little bit different...
Putting a static declaration outside of any #interface in a header (.h) file will create a different variable in each implementation (.m) file you include the header in - not what you want in this case.
So static on a declaration creates a variable whose lifetime is that of the whole application execution but which is only visible within the compilation unit (e.g. the implementation file) in which it appears - either directly or via inclusion.
To create a global variable visible everywhere you need to use extern in the header:
extern NSString *id;
and in your implementation repeat the declaration without the extern:
NSString *id;
As to what is wrong with global variable vs. class methods, that is a question on program design and maintainability. Here are just a few points to consider:
With a method the value cannot be changed unless you provide a setter method as well as getter method. Variables are always read-write.
Namespace pollution: a class method is only valid when paired with its class name ([YourClass id]); the variable name is valid everywhere it's included simply as id; that both pollutes the name space and loses the connection between id and YourClass - which leads us to...
Encapsulation: globals variables break strong encapsulation, and encapsulation aids program design and maintenance - this is a big topic.
That said, there can be a time and a place for globals, sometimes...
After question updated
A static variable declared in the implementation is effectively a "class variable" - a variable shared by all instances of the class.
The pros'n'cons of a class variable vs. setter & getter class methods are exactly the same as the pros'n'cons of an instance variable vs. properties & setter/getter instance methods.
Class setters/getters allow for validation and other logic to be executed on each read/write; and localization of memory management - in short the abstraction and encapsulation benefits of any method.
Therefore whether you use a variable or a setter/getter depends on your application. It is the same question as whether you use an instance variable or setter/getter/property.