Suppose my class has one method which has to call some other recursive method from inside it.
My .h file would look like this:
class MyClass()
{
public:
void foo();
};
My question is, which of these implementations would be better (ignoring the infinite loops):
namespace
{
void myRecursiveFunction()
{
myRecursiveFunction();
}
}
void MyClass::foo()
{
myRecursiveFunction();
}
or
void MyClass::foo()
{
std::function<void()> myRecursiveFunction =
[&] ()
{
myRecursiveFunction();
};
myRecursiveFunction();
}
, giving that myRecursiveFunction()will only be called from foo() ?
Of course, in the real world myRecursiveFunction() does something. I just wanted not to populate the code with unneeded information.
Is it ok for all my class to have access to myRecursiveFunction if I only use it in one method?
std::function pros:
If the recursive function is only called from that function, then it's scope is well limited. The anonymous namespace is visible to the whole translation unit. It's OK for the function to be visible to the rest of the tranlation unit, so this is arguably only a slight advantage.
std::function cons:
A simple function has simpler syntax than a lambda.
std::function would probably have some small overhead.
If you define the std::function inside foo, then the recursive function is not reusable outside it. Which is fine, if it's not reusable anyway.
Won't work in a pre-c++11 standard.
Which is better depends on what you need and what you prefer. I would prefer a simple function in most cases.
Yes it's OK to define myRecursiveFunction() in an anonymous namespace, even if its visible to all your class' implementation, even if there is only MyClass::foo() who calls it.
Presumably, you control your class implementation, and you won't call myRecursiveFunction() where there is no reason to. This goes for all functions: would you call abort() where you should not? Though it's accessible by your whole class.
Using a recursive local lambda only adds a layer of inference and makes the code more complex to read. If this is a time-critic part of your program, you probably make it slower by using an std::function.
Related
It comes across as odd to me that local function definitions are illegal. As things stand now, I doubt it would be too hard to implement, and the erasure of what could be a potential feature (like in python for example) for no reason at all seems strange, especially for a language like C++, where you can shoot yourself in the foot if you want to. The illegality of local function definitions seems doubly so strange if things like this are allowed.
int main()
{
void func(); // Allowed?
class BypassRules {
public:
static void func() { return; }
};
BypassRules::func();
func();
return 0;
}
void func() { return; }
Oddly enough, local function 'Declarations' are allowed, but definitions are not. And the rule on local function definitions not being allowed can be easily bypassed by writing a class encapsulator. So, could I have some clarification? Why are local class definitions classified as 'illegal' in C++?
Oddly enough, local function 'Declarations' are allowed, but definitions are not. And the rule on local function definitions not being allowed can be easily bypassed by writing a class encapsulator. So, could I have some clarification? Why are local class definitions classified as 'illegal' in C++?
Illegal because they don't make much sense, whether it may be defining a function inside a function or a class inside a function like main().
But then you can always use workarounds, such as:
For functions you can always use a lambda, which acts as an anonymous temporary function, can be called inside main plus be used within function parameters as well.
It can be invoked whenever necessary and subsequently discarded like a throw-away function, but it does the job - whatever you would expect from a function.
Example:
int main()
{
// Define within the scope of main()
auto temp = [](int x)
{ std::cout<< x;
}
temp(10); // call like a function
}
For classes, use static functions, (being local to the translation unit) with public access specifiers (as you did in your question).
Example:
int main()
{
class temp
{ public:
static void a()
{ std::cout<< 10;
}
};
temp::a();
}
Output for both cases: 10
Provided there are alternatives approaches like the ones above to define a function/class/struct inside main(), there isn't really much of a point to make them legal. ¯\_(ツ)_/¯
In Haskell there is a constant called undefined that you can use to
declare a function without defining it (i.e. a function prototype with an empty body) as with squarein
square :: Int -> Int -- declaration
square = undefined -- empty definition
main = putStrLn.show.square $ 3
This is tremendously useful to defer the work on square and focus on getting the main function right first, because the Haskell compiler makes sure that the whole file compiles as if square was defined.
The C++ equivalent is
#import <iostream>
int square(int x){
//TODO incomplete
return 0;
}
int main() {
std::cout << square(3);
}
My intention is to invoke a compiler like clang++ as a typechecker for main alone and work on square later. Imagine that square really is one of many not-yet-defined complex functions that return a complex data structure with a non-trivial constructor. I would have to write a lot of code to create returnable objects just to get the functions to compile.
Is there something quick-and-dirty in C++ similar to undefined?
Thank you #molbdnilo.
Using throw is concise and works perfectly:
int square(int x) {
throw("undefined");
}
You can also use assert as following:
int square(int x)
{
assert(0);
}
This has the advantage that it can't be caught and will always fail. This will protect you better in case you forget to implement the function.
C++ has pure virtual functions, for use in abstract base classes.
class foo {
virtual void bar() = 0;
};
The function foo::bar() cannot be called, and indeed a foo object cannot even be created, but it can be overridden in a derived class of foo. You can, however, give a definition for it that derived classes inherit by default.
Another thing in C++ that’s somewhat similar to undefined is an uninitialized function pointer. A safer, more modern solution might be a lambda expression or static stub function that aborts the program.
The meaning of undefined in actual use is something like: a placeholder that will crash the program if you try to actually call it, but which compiles correctly and will be type-checked. For individual object files, declaring an extern prototype for a function that isn’t defined anywhere will do the job. If you’re linking the whole program, there has to be some kind of definition (although function pointers can get around that, at the cost of safety), but it can be a stub.
As weird as the question sounds, I meant when a class is defined solely in cpp file because it is more of less a helper class for the implementation of another class and doesn't deserve to be in its private section. I understand that inlining constructor and destructors is a bad practice, but what about this situation, demonstrated as follows? Thank you very much
EDIT: I should have reworded it. In some cases inlining constructor and destructors causes bloated code unexpectedly(as discussed in Effective C++ Item 30, "Understand the ins and outs of inlining"). However I would like to know if such inlining demonstrated resulted in that as well
// my_class.cpp
#include <my_class.h>
namespace {
class Helper
{
public:
Helper() {...} // should I inline the constructor here?
~Helper() {...} // should I inline the destructor here?
};
/* alternative implementation looks like
Helper::Helper()
{...}
Helper::~Helper()
{...}
*/
} // end of anonymous namespace
// implementation of my_class
This is probably a moot point. Another discussion here discusses this to a good degree. The basic take away is that the compiler may ignore your "inline" or it may choose to "inline" the function/constructor/whatever without your input. The inline command is simply a suggestion that the compiler is free to ignore.
TL;DR Go for it; it probably isn't going to make a difference.
It's fine either way. If ever a helper function becomes a performance bottleneck because it is not inlined, you might consider making it an inline function.
Many times I find that a single instance of the Helper class is adequate for use by the main class. Hence, whether the constructor and destructor are inlined or not does not make any difference at all.
namespace {
class Helper
{
public:
Helper() {...}
~Helper() {...}
};
// The sole instance of the Helper class.
static Helper helper;
}
void main_class::foo()
{
helper.foo();
}
I am currently implementing some utility functions for implementing some libraries I am working on. I was forced to choose between segmenting the functions as static members as part of a class definition within a more general namespace, or enter more specific namespace and then define the functions. I choose the former feeling as it was more flexible in the way those utility classes may be drawn into scope (using or inheritance) though I was unsure whether there was any overhead associated with this design choice or not:
Is
namespace Utilities {
struct CharUtil {
static void foo();
}
}
Utilities::CharUtil::foo();
slower than
namespace Utilities {
namespace CharUtil {
void foo();
}
}
Utilities::CharUtil::foo();
?
Is the former faster using inheritance?
There is no difference at all between the two cases, except for functions' mangled names. Static functions do not have this pointer as hidden argument. The compiler generated code for both functions will be the same.
In order to improve code readability, sometimes I use "alias methods". These are basically methods that all do the same thing (at least in the base class; derived classes may do it differently) with different names, that enhance code readability for the class user depending on the context. Consider the code below for an example:
template <typename T>
class Foo {
public:
T bar() { /* Lots of stuff here */ }
inline T bar_alias1() { return this->bar(); }
inline T bar_alias2() { return this->bar(); }
};
Of course, if Foo::bar() was a small function, one would simply duplicate the code in all the alias methods. However, since the code may be relatively large, code duplication should be avoided, hence why the alias methods are declared as inline. But I know that the compiler does not guarantee that any function declared as inline would actually end up being expanded at compile time.
So my question is, am I introducing any performance overhead by creating these alias methods? In the code below:
Foo<BIG_OBJECT> foo;
BIG_OBJECT bo1 = foo.bar();
BIG_OBJECT bo2 = foo.bar_alias1();
Would calling foo.bar() be faster than calling foo.bar_alias1() assuming the object being passed is relatively large? Are there redundant copies of the object being made when Foo::bar_alias1() calls Foo::bar()?
I'm using Visual Studio 2010 as my compiler.
Assuming the aliased functions are inlined - and they should given the size.
There shouldn't be any performance overhead. The code-size won't increase either if the compiler decides to omit the function code and inline all calls to it.
(I'm referring to the inlining of bar_alias1(), bar() itself won't necessarily be inlined if it's large.)
However, this doesn't apply if the functions are virtual.
In C, I would do this more directly with preprocessor, but I'm not sure how appropriate that is in C++.