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();
}
Related
I usually declare in header file and implement in cpp file, but now I am doing an assignment, and, apparently for brevity, the instructor doesn't want me to do that, but insists that I write all the code in header files.
So, what is the best way to do that?
For classes, should I declare everything first, and then go to the bottom of the page and start implementing?
class myClass
{
void myMethod();
}
void myClass::myMethod() { //.... }
or should I just implement as I declare
class myClass
{
void myMethod() { //... } ;
}
What about free functions?
And when should I write "inline"?
or should I just implement as I declare
Yes, implement them in class, not out of class. When the (questionable) reasoning of your instructor for putting everything into a header refers to brevity, this is obviously the way to go.
What about free functions?
Same as with member functions, define them on the go.
And when should I write "inline"?
You should add inline to all ordinary free functions. It's unnecessary for function templates or in-class member function definitions. When you can use C++17, consider inline variables, too.
Scott Meyer states in Effective C++: Item 30: Understand the ins and outs of inlining that constructors and destructors are often worse candidates for inlining.
Defining functions inside a class definition, requests (not commands) them implicitly to be inline. Depending on the quality of your compiler, the compiler decides whether or not (explicitly or implicitly) defined functions be actually inlined or not.
Taking all these into account, is it a better practice to explicitly define empty/copy/move constructors, copy/move assignment operators and destructors as default (i.e. with the default keyword) inside the body files than inside the header files? After all, default deals purely with implementation as opposed to the dual delete?
Without ever reading "Effective C++: Item 30" I can definitely tell that it makes perfect sense to define empty-looking ctors/dtors inside .cpp:
// MyClass.h:
class MyClass
{
public:
MyClass();
~MyClass();
...
}
// MyClass.cpp:
MyClass::MyClass() = default;
MyClass::~MyClass() = default;
This might look like waste for digital ink, but this is exactly how it has to be done for heavy classes that have large inheritance list or lots of non trivial members.
Why do I think it has to be done like this?
Because if you don't do that, then in every other translation unit where you create or delete MyClass compiler will have to emit inline code for entire class hierarchy to create/delete all members and/or base classes. In giant projects this is usually one of main reasons for builds that takes hours.
To illustrate, compare generated assembly with non-inline ctor/dtor and without. Not that if you have multi-level inheritance with virtual classes then amount of generated code grows very fast. Some call it C++ code bloat.
Basically if you have inline function in your class and you use that function in N different cpp files (or worse in some header files that are used by many other cpp files) then compiler would have to emit that code N times in N different object files, and then at link time merge all these N copies into one version. This rule applies basically to any other function, however, it's not very common to make large function inline in header files (because it's just bad). The issue with constructors, destructors and default assignment operators etc is that they may look like empty or no c++ code at all, while they actually need to perform that same operation recursively for all members and base classes and all of that results in very large amount of generated code.
Another use case of defining a destructor = default inside the body file, is the PImpl idiom in combination with std::unique_ptr.
header file: example.hpp
#include <memory>
// Example::Impl is an incomplete type.
class Example
{
public:
Example();
~Example();
private:
struct Impl;
std::unique_ptr< Impl > impl_ptr;
};
body file: example.cpp
#include "example.hpp"
struct Example::Impl
{
...
};
// Example::Impl is a complete type.
Example::Example()
: impl_ptr(std::make_unique< Impl >())
{}
Example::~Example() = default; // Raw pointer in std::unique_ptr< Impl > points to a complete type so static_assert in its default deleter will not fail.
At the point in the code where std::unique_ptr< Impl > is destroyed, Example::Impl must be a complete type. Therefore, implicitly or explicitly defining Example::~Example in the header file will not compile.
A similar argument applies for the move assignment operator (since the compiler-generated version needs to destroy the original Example::Impl) and for the move constructor (since the compiler-generated version needs to destroy the original Example::Impl in case exceptions).
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should I write the keyword 'inline' for a function/method?
I am not 100% sure, but as far as I know, if I declare a function on an hpp file with the body it will be treated as it is marked as inline(the compiler will decide what to do), I mean:
//myfile.hpp
class StackOverflow{
public:
void overflow(){_overflow = true;}
...
}
would be the same than:
//myfile.hpp
class StackOverflow{
public:
***inline*** void overflow(){_overflow = true;}
...
}
If I am wrong then the question is over, but otherwise, I really like to mark as inline a function even it is not necessary, does general code style guidelines say soemthing about it?
Thanks so much
As the mention of the keyword inline in this context gives no information whatsoever, leave it out. It’s simply visual clutter.
If there were an option to make an inline-defined function non-inline, this would be a different matter (consider private-by-default as such an example): here, it could be argued that even though it’s the default, making the choice explicit makes it easier to understand. But there’s no choice here. No matter what you do, a member function defined inside the body of a class is inline.
In fact, marking it explicitly as inline would be akin to providing other inferred information. You wouldn’t write the following, would you?
#define member
#define function
class StackOverflow{
public:
member function inline void overflow() { _overflow = true; }
}
Defining a function body inside the class definition makes the function implicitly same as marking it with keyword inline.
As a matter of coding style,
Just defining the function body inside the class is not a good practice.
class Foo {
public:
void method(); ← best practice: don't put the inline keyword here
...
};
inline void Foo::method() ← best practice: put the inline keyword here
{ ... }
This C++ Faq explains the rationale:
class Fred {
public:
void f(int i, char c)
{
...
}
};
Although this is easier on the person who writes the class, it's harder on all the readers since it mixes "what" a class does with "how" it does them. Because of this mixture, we normally prefer to define member functions outside the class body with the inline keyword.
The insight that makes sense of this: in a reuse-oriented world, there will usually be many people who use your class, but there is only one person who builds it (yourself); therefore you should do things that favor the many rather than the few.
If you declare a function as inline inside of the class, for one just like the register keyword, it's open for the compiler to determine (it's a suggestion) if it's a wise optimization to make. Generally, it's a rule of thumb to use inline functions programmed inline inside of the class itself, however it can be done in the implementation of the class as well, though is not common and the only benefit it offers is the linkage, should you decide to pass out the .h/.hpp file as an API header.
When I use the pimpl idiom, is it a good idea to put all the methods definitions inside the class definition? For example:
// in A.h
class A {
class impl;
boost::scoped_ptr<impl> pimpl;
public:
A();
int foo();
}
// in A.cpp
class A::impl {
// method defined in class
int foo() {
return 42;
}
// as opposed to only declaring the method, and defining elsewhere:
float bar();
};
A::A() : pimpl(new impl) { }
int A::foo() {
return pimpl->foo();
}
As far as I know, the only problems with putting a method definition inside a class definition is that
(1) the implementation is visible in files that include the class definition, and
(2) the compiler may make the method inline.
These are not problems in this case since the class is defined in a private file, and inlining has no effect since the methods are called in only one place.
The advantage of putting the definition inside the class is that you don't have to repeat the method signature.
So, is this OK? Are there any other issues to be aware of?
I think you answered your own question : both solutions are equivalent.
However, I wouldn't be so sure that 'inlining has no effect since the methods are called in only one place' : an additional call could exists when the functions are not inlined. But chances are that the compiler is smart enough to optimize them away from the one-line forwarding calls in the outer class.
In the end, I believe it's just a matter of taste.
Advantages:
all code of the class is localized
Disadvantages:
for larger classes: when scrolling is needed, it becomes more difficult to know to which class the function belongs.
dependencies are more easily solved when functions reside after all class declarations. Otherwise, it might be needed that some class declarations are moved after others and some functions still have to be moved after the class declaration when there are mutual dependency of internal classes.
Usually I don't add methods to the Impl inner class, but I can't see any issue if you define the methods inline. It seems to me much more readable than having seperate declaration and definition.
Whether the compiler inlines the methods depends on the compiler and the passed parameters.
In the case of the pimpl idiom, I don't think it matters whether the methods are defined within the Imp's body or not. I personally like them defined outside, because it is easy to see what is really important (like member variables and list of methods).