I saw that in some programs it is recommended the use of public variables instead of get and set functions for a better performance. I know that this is considered a bad practice. I also know that the compiler could make the get and set inline. Doesn't this mean that they behave like a variable with no performance fall-outs?
The compiler will most probably inline these functions (see how), and there will be no function call overhead. I would avoid the getter, setter, and public member variables and instead think why these are used and provide a function to do that in that class. Most of the getter, setter, and public member variables can be removed this way.
You can always expect compilers to inline trivial getters and setters and so you'll get identical performance.
There can be differences though, such as not being able to get a pointer or reference to the private member when using getters/setters if you're returning by value. Also, setters may have an extra copy or move operation.
Anyway, if you want public access then just use public variables. They are best practices.
They should be the same performance-wise, if the compiler really choses to make them inline. The inline keyword is just a hint for the compiler, it must not strictly obey it, and vice-versa: it can make a function that is not marked with inline keyword, an inline one.
However, if for some reason the compiler will not make them inline, you will obviously lose some performance on the calls.
Related
I write code like
template <typename XAxis, typename YAxis>
class Interpolation {
public:
using x_value_type = typename XAxis::value_type;
using y_value_type = typename YAxis::value_type;
Interpolation(const XAxis& x_axis, const YAxis& y_axis)
: _x_axis(x_axis), _y_axis(_y_axis)
{}
public:
y_value_type interpolate(const x_value_type& x) const;
private:
const XAxis _x_axis;
const XAxis _y_axis;
};
when i want to intent that member variables is immutable.
I feel a little anxious why I think that I might be known above code is illegal or bad code by some reason.
How do you think that constant member variables are beneficial or not?
Please tell me with your reason.
A practical advantage of const members is that unless they're of a class with user defined default constructor, they have to be explicitly initialized. So a ¹standard-conforming compiler will catch any missing initialization. It's also an advantage that const members express the intended functionality, namely no change over the lifetime of an object, and so help the compiler to detect any code that otherwise would (erroneously) change the values.
On the other hand, which can more important, with the default functionality they prevent copy assignment and moving.
These considerations also apply to reference data members, which can be regarded (conceptually) as auto-dereferenced const pointer members.
For client code, but not the class' own code, the logical const-ness, the immutability, can be expressed by using non-public non-const data members with const accessor member functions.
¹ Unfortunately Visual C++ 2015 accepts at least some cases of uninitialized const member that doesn't have a user-defined default constructor, so as of this writing one can't be 100% sure that the compiler will catch missing initializations.
const member variables do have some minor benefit. Because the compiler knows that their const, and their value cannot change, the compiler might be able to better optimize any code and expressions that reference the const class members.
A more practical benefit is that any logical code errors, that attempt to modify, these class members will now fail to compile. Otherwise, the logic error may not be immediately apparent, and result in burning up a lot of time later, tracking it down.
Const members:
prevent copy and move assignment
are known never to change
make your object truly immutable, which has the following advantages:
-
offers performance advantages when sharing data in a multi-threaded program.
allows the compiler to be very aggressive with redundant load optimisations
You could achieve the same with const accessors to mutable data.
That's true, at the expense of more (redundant) code to maintain.
To me it seems unnecessary as you can always have const member functions to make sure you don't modify the fields. Also, having const member variables also disable move semantics which means an object of that type must always be copied and can't be moved from. I would refrain from doing it.
My question title pretty much asks it all. I've recently found out that it is good programming practice in C++ to pass many values by const reference and mark certain methods in classes as a constant method. Right now, I have a library that I have been writing for myself for a while now that has absolutely no const-correctness, so I'd like to start rectifying that little by little.
In what specific scenarios should I make a method constant? So far I know "getter" methods should generally be made constant (since the code in one shouldn't modify any class variables), but do I do that for all methods that are considered getters, or only specific ones? And outside of getter methods, what other scenarios should methods be made constant?
but do I do that for all methods that are considered getters, or only specific ones?
You should do that for all methods that don't modify the non-mutable members. They include not only getter functions but also any overloaded operator functions, such as operator==, operator!=, operator<.
When should I make a method constant?
As a rule of the thumb, you should make a method constant whenever none of the object's member variables are altered.
As an additional guideline, you should do this only when you are sure the method will not be altered in the future to change member variables.
Ultimately, if you are planning to make a method affect member variables, it should be non-constant. Otherwise, it should be constant.
One thing I really dislike in programming is ambiguity with variables names. I'd like to always use the this keyword to access class members, but I often forget to use it in some cases, which leads to some inconsistency.
So I'd like to be forced to use the this keyword when accessing a class member. Would this be a bad idea? I'm thinking there might be a compiler option for that, but I can't find anything about it. I'm using the g++ compiler.
This is a circular problem. You want the compiler to error out and inform you when you're accessing a class member without prefixing this->, so that you cannot be accidentally referring to a local variable or function argument instead … but for that exact same reason, how is the compiler supposed to know that you really intended to access the member? And, if you didn't, how would you access the local variables or function arguments?
C++ is simply not designed this way. Some languages, such as PHP, require that you must use this to access members and any other access is treated as an attempt to read local-scope variables (whether they exist or not), but C++ does not have that. And there is no compiler switch to make it happen. If this worries you, avoid re-using the names of variables!
In short, this is a non-problem that cannot be solved.
I know that we should declare a function as static in a class if its a utility function or if we have to use in a singleton class to access private static member.
But apart from that does a static function provide any sort of compiler optimization too since it doesn't pass the "this" pointer? Why not just use the utility function through an already instantiated object of class? Or is it just a best practice to make utility functions as statics?
Thanks in advance.
The "non-passing-this" optimization can probably be done by the compiler once you turn the optimizations on. As I see it, a static function has rather idiomatic uses:
Implementing modules. There is a bit of overlap here with namespaces, and I would rather use namespaces.
Factories: you can make the constructor protected/private and then have several static functions (with different, explicit names) creating instances.
For function pointers: static functions do not require the slightly more complicated syntax of pointer to member function. That can be a plus when interacting with libraries written for C.
To keep yourself from using this and have the compiler to enforce it. It makes sense sometimes. For example, if you have a commutative operation that takes two instances, a static function that takes the two instances would emphasize (in my opinion) that the operation is commutative. Of course in many cases you would rather overload an operator.
In general a static function will ease namespace and "friend" clutter by prefixing an otherwise ordinary function with the name of a class, presumably because both are tightly related.
Static exists to associate a method with a class, rather than either:
Associating it with an instance of that class (like writing a normal, non-static member function).
Keeping it in the global namespace or whatever namespace you would otherwise be in (like declaring a function just in the file, not in a class).
Static says that 'conceptually this is something tied to/associated with this class, but it does not depend on any instance of that class'.
In more formal terms: a static member function is the same as a function declared outside of a class in all ways other than that it is part of that class's namespace and in that it has access rights to that class's private/protected data members.
Going back to your question:
There is no optimization gain here.
Utility function has nothing to do with it. It's whether or not it makes sense to scope the function in the class itself (rather than an instance of it).
It does not 'pass the this pointer' because there is no instance to speak of. You can call a static member function without ever invoking that class's constructor.
Now I have been learning about inline functions and I encountered something that really made me confused
See this class
class Nebla{
private:
int x;
public:
inline void set(int y){x=y;}
inline void print(){cout<<x<<endl;}
};
it has a private data member: int x;
And it has two public inline functions: set(int y) and print()
Now since they two functions are inline, when they are called the compiler replaces the function call with the contents of the function.
So if I do this
Nebla n;
n.set(1);
n.print();
since the two functions are inline, It should be the equivalent of this:
Nebla n;
n.x=1;
cout<<n.x<<endl;
but wait a second, x is private. Therefore, this shouldn't work.
But it does and I'm confused why it does work although normally you cant access private members from outside the class?
Can anyone explain to be why you can access private data members from outside the class but when a member function is inline it can although inline just replaces the function call with the contents of the function?
Data member protection is purely conceptual. It exists only at the compiler level. It is checked and enforced when the compiler translates the source code. Once the code is compiled, there's no difference between public and private data members anymore, i.e. there are no physical mechanisms that would enforce access control and prevent access to private data members.
Member access is enforced by the compiler in accordance with the language specification. The language specification states that class member functions (regardless of whether they are inline or not) have access to private members of the class. So the compiler allows that access. Meanwhile, other functions are prohibited such access, so the compiler complains about it.
In your example you are accessing private data member from a member function. That is allowed, so the code compiles, i.e. the compiler does not complain. What happens later in the generated machine code, after the function gets inlined, is completely irrelevant. That's all there is to it.
You misunderstand how inline works. The compiler inlines the logic of the code, not the actual text of the code.
Can anyone explain to be why you can access private data members from outside the class but when a member function is inline it can although inline just replaces the function call with the contents of the function?
Because the contents of the function are the contents of the function. They don't stop being the function just because they've been inlined. You are allowed to access private member variables from inside a member function. When a member function is inlined, its code is still inside the member function because the function is inlined.
First of all, whether or not it gets inlined is up to the compiler. In a lot of cases it will decide is not the best thing to do.
Second, in the case it does inline it, it does so with a compiled binary, product of the behavior described in the C++ source code, not the actual text.
Morbo says the inline keyword doesn't work that way.
Morbo says that the inline keyword says that symbol conflict at linker time involving this function should be ignored, and that all functions whose implementation is within the declaration of the class are implicitly inline.
Morbo is wise. You should listen to Morbo, even if there is a minor technical additional meaning of inline that involves taking addresses.
More seriously, inline just let's you put definitions of the implementation into a header file. Actually making the code inline is thus easier because it doesn't have to happen at link time (and most C++ linkers are too lazy) but it does not cause the code to be inline.
And finally privacy is conceptual, it is not enforced by the C++ run time. It is just enforced at compile time by telling you that something is out of bounds.