cppcheck error doesn't match what I see - cppcheck

I run cppcheck and I get this message:
"Member variable
'i_refvec::data_' is not assigned a value in
'i_refvec::operator='."
The code is from the template numerical toolkit (TNT). I think I see these variables getting initialized, but I still get the complaint.
Help?
The pertinent function (starting at line 155) goes:
template <class T>
i_refvec<T> & i_refvec<T>::operator=(const i_refvec<T> &V)
{
// Do nothing if we're pointing at ourselves
if (this == &V)
return *this;
if (ref_count_ != NULL)
{
(*ref_count_) --;
if ((*ref_count_) == 0)
destroy();
}
data_ = V.data_;
ref_count_ = V.ref_count_;
if (V.ref_count_ != NULL)
(*(V.ref_count_))++;
return *this;
}

I am a Cppcheck developer.
It looks like a false positive to me also. I wonder if you can reduce it to a short example code which reproduces the problem.. and then report a ticket here: http://trac.cppcheck.net.
False positives are often caused by some tiny detail. Possibly somewhere else. Therefore it's hard to say why this might fail.
If you want to create an example code that reproduce the false positive, it's best to reduce your original code (removing includes, classes, methods, etc).

Related

How do you re-write a C++ empty if statement with side-effects

I have code that does something like this:
//datareader.cpp
if (populateFoo(dataReader, foo))
else {
// Do other things with the reader.
}
//foo.cpp
bool populateFoo(const DataReader &dataReader, Foo &foo)
{
if (dataReader.name() == "bar") {
foo.bar() = dataReader.value();
return true;
} // More similar checks.
return false;
}
I feel like it's misleading to have an if statement with conditions that have side-effects. However, I can't move the body of the populateFoo function into datareader.cpp. Is there a good way to restructure this code so we get rid of this misleading if statement, without duplicating the body of populateFoo()?
Do you have a strong hatred of local variables? If not:
bool populated = populateFoo(dataReader, foo);
if (populated)
{
// Do things
}
else
{
// Do other things
}
The compiler will almost certainly emit exactly the same code, so performance shouldn't be an issue. It's a readability/style choice, ultimately.
The obvious solution seems like storing the result of populateFoo and using it for determining whether populateFoo was successful:
bool fooPopulated = populateFoo(dataReader, Foo);
if (!fooPopulated)
//Do other things with reader.
However, I don't find the original difficult to understand, and it's a fairly well-established practice to both modify values and test the success of the modification in the same line. However, I would change it to:
if (!populateFoo(dataReader, Foo)
//Do other things with reader.
How about:
if (!populateFoo(dataReader, foo)) {
// Do other things with the reader.
}
Edit: The title of the question suggests it is the fact the if statement is empty that bothers you but the body seems more that it is the side effect that is the concern. I think it's fine in C++ to have conditions in if statements that have side effects but this won't solve your issue if you want to avoid that.
Having conditions with side-effects is quite common - think about calling a C API and checking its return code for errors.
Usually, as long as it's not buried in a complicated expression where it may be missed by the casual bystander, I don't bother to do particular refactorings, but, in case you wanted to make it extra clear (or document what the return value is, which is particularly useful in case of booleans) just assign it to a variable before the branch - or even just a few comments may help.
You could split the populateFoo function into two, a const check function (shouldPopulateFoo) that checks the condition, and another non-const function that performs the actual modifications (populateFoo):
//datareader.cpp
if (shouldPopulateFoo(dataReader)) {
populateFoo(dataReader, foo);
}
else {
// Do other things with the reader.
}
//foo.cpp
bool shouldPopulateFoo(const DataReader &dataReader) /* const */
{
return (dataReader.name() == "bar");
}
void populateFoo(const DataReader &dataReader, Foo &foo) /* non-const */
{
assert(shouldPopulateFoo(dataReader));
foo.bar = dataReader.value();
}
Note that when using these functions as class methods, you could declare the check function const.
How about:
if (populateFoo(dataReader, foo) == false) {
// Do other things with the reader.
}
It is very readable, I often see code where the returned value from function is a signal to the caller for branching in the caller. The else block with empty if block bothers me more then the side effects inside the if (). There is a sense of reverse logic, which is alway less readable.

Handle errors C++

So, I have a simple library-class and this class has some methods that return some values like code errors.
User_program
MyClass go(arg1, arg2)
if(go.execute() == 0)
std::cout << go.result();
And my class has something like this
My class
int execute()
{
if((temp = doBar()) != 0)
{
return temp;
}
return SUCCESS;
}
int doBar()
{
if(foo == 1)
return DIVIDION_BY_ZERO;
if(fzz == 0)
return OPERATION_ERROR;
}
And so on. So, is there any method to make errors more helpful, I've heard about enum with const for errors, but I don't understand how to implement it.
Thanks.
Not sure that I understood the question right, but here is few moments.
In your case enum`s is way to store all definitions of const
values like (SUCCESS, DIVIDION_BY_ZERO, etc) in one place (even in
one translation unit). And also compiletime validation of types.
read more here:
[1]
2) If intresting how implemented some error check there is no need
to go far.
First of all look at C handling errors in libc [2]
In ISO C++11 presented [system_error]
And typical error handling in libs released special for (almost) each type like in Qt [QNetworkReply]
And also using exceptions(and dark side of C++ like RTTI) in libs is bad idea. But take this link too [3]

Dereferencing a set iterator causes a seg fault

I'm trying to determine why the following code is throwing a segfault on line 10 (where we dereference upgradeIter).
bool UpgradeType::isAffected(const UnitType *unitType) const{
if(std::find(effects.begin(), effects.end(), unitType)!=effects.end()) return true;
// Check if the unit has any of the affected tags
std::set<string>::iterator upgradeIter;
for(upgradeIter = tags.begin(); upgradeIter != tags.end(); ++upgradeIter) {
std::set<string>::iterator unitIter;
for(unitIter = unitType->getTags().begin(); unitIter != unitType->getTags().end(); ++unitIter) {
string unitTag = *unitIter;
string upgradeTag = *upgradeIter;
if(unitTag == upgradeTag) return true;
}
}
return false;
}
The context is that UpgradeType has "tags" (just a set of strings). Units also have tags. If a unit shares at least one tag with the upgrade, then the unit is affected by the upgrade.
I don't see any reason why the mentioned line would crash. It seems to me that there is no circumstances under which the iterator could be invalid.
In other parts of the code that display the contents of tags (used in very similar ways), the output is as expected.
EDIT: I've just found out that unitType->getTags().size() is 0. So I don't understand why the body of the for loop is even executed. unitIter != unitType->getTags().end(), however, is evaluating to true. This seems off.
I managed to find a solution to this with the help of Yggdrasil on this site (which also means that Matt McNabb in the question's comments was correct). Quoting his post below:
As someone more or less mentioned on stackoverflow: Change getTags() to return a reference, not a value/copy.
const set &getTags() const {return tags;}
Be aware that the return type is const, so use a const iterator.
Not sure if that's all, but you don't want a (deep) copy there, for sure. The iterator gets out of bounds because you check against the end of a different set. Every call to getTags() gets its own copy.

C++ segfault at the end of a for loop

This code is segfaulting and I can't really figure out why. When I use gdb it segfaults at the end of the function (the curly brace). So that doesn't really give me a lot of information as to what's going on. Here's the code, I'll provide extra info if needed.
typedef std::list<Ground> l_Ground;
void Player::y_collisions(l_Ground grounds) {
for (l_Ground::const_iterator ent = grounds.begin(); ent != grounds.end(); ent++) {
if (getGlobalBounds().intersects(ent->getGlobalBounds())) {
in_air = false;
velocity -= gravity;
}
}
}
EDIT: Upon closer inspection, it's probably segfaulting at the end of that for loop. Which still doesn't really make sense because of the way the for loop is written. It shouldn't go beyond the end of the list.
EDIT2: This will work because of the answer below.
typedef std::list<Ground> l_Ground;
void Player::y_collisions(const l_Ground& grounds) {
for (l_Ground::const_iterator ent = grounds.begin(); ent != grounds.end(); ent++) {
if (getGlobalBounds().intersects(ent->getGlobalBounds())) {
in_air = false;
velocity -= gravity;
}
}
}
You were passing the grounds parameter by value. That means a copy of the list was made. Apparently your Ground class have a broken copy constructor, which makes the getGlobalBounds() method referring to some invalid pointer, which caused the crash.
You should almost never pass a big object by value unless you want to immediately copy it. Always train yourself to type const & all the time :).

C/C++ (Other Languages Too?) Conditional Early Return Good Code Practice

Recently, I was reviewing some code I maintain and I noticed a practice different than what I am used to. As a result, I'm wondering which method to use when performing an early return in a function.
Here's some example:
Version 1:
int MyFunction(int* ptr)
{
if(!ptr) { // oh no, NULL pointer!
return -1; // what was the caller doing? :(
}
// other code goes here to do work on the pointer
// ...
return 0; // we did it!
}
Version 2:
int MyFunction(int* ptr)
{
if(!ptr) { // oh no, NULL pointer!
return -1; // what was the caller doing? :(
} else { // explicitly show that this only gets call when if statement fails
// other code goes here to do work on the pointer
// ...
return 0; // hooray!
}
}
As a result, I'm wondering which is considered the "best practice" for those of you who have endured (and survived) many code reviews. I know each effectively does the same thing, but does the "else" add much in terms of readability and clarity? Thanks for the help.
The else would only add clarity if the else clause is short, a few lines of code at best. And if you have several initial conditions you want to check, the source gets cluttered very quickly.
The only time I would use an else if it is a small function with a small else, meaning less than about 10 source lines, and there are no other initial checks to make.
In some cases I have used a single loop so that a series of initial checks can use a break to leave.
do {
...
} while (0);
I am loathe to use a goto which is practically guaranteed to get at least one true believer of goto less programming up in arms.
So much would depend on any code standards of your organization. I tend to like minimalism so I use the first version you provide without the else.
I might also do something like the following in a smaller function say less than 20 or 30 lines:
int MyFunction(int* ptr)
{
int iRetStatus = -1; // we have an error condition
if (ptr) { // good pointer
// stuff to do in this function
iRetStatus = 0;
}
return iRetStatus; // we did it!
}
The only problem with returns in the body of the function is that sometimes people scanning the function do not realize that there is a return. In small functions where everything can be pretty much seen on a single screen, the chance of missing a return is pretty small. However for large functions, returns in the middle can be missed especially large complex functions that have gone through several maintenance cycles and had a lot of cruft and work arounds put into them.