This seems a bit strange to me. Since a static method can have an instance of the class, one naturally expects that the compiler should not allow calling static methods inside the constructor. But I have tested the following code with every compiler and ironically, none of them gave me a single warning. Although in execution time they all throw exceptions. Am I missing something here?
#include <iostream>
class Foo
{
public:
inline Foo()
{
std::cout << "testing: var = " << bar() - 1 << '\n';
}
~Foo(){}
static int bar()
{
Foo f;
f.var = 10;
return f.test();
}
private:
int var;
int test()
{
return var + 1;
}
};
int main()
{
Foo foo;
return 0;
}
Live example
It is not illegal to call static functions from within the constructor. Only, you are getting a stack overflow, if you do it like you do. This results in
Foo() calls bar();
bar() calls Foo();
Foo() calls bar();
bar() calls Foo();
...
Until no stack is left.
This is exactly the same as if you had:
void f1();
void f2()
{
f1();
}
void f1()
{
f2();
}
int main(int, char*[])
{
f1();
return 0;
}
Only two global functions, nothing more. Would have been all the same in C, too (but you have do declare void f(void) there), or Java, C#, perl, python, ...
What warnings are you expecting? What you've written is an infinite recursion which has nothing to do with static member functions. You can do it with any other function inside or outside a class.
Static functions are not much different from the free ones. So free functions should also be banned from constructor? There is no point in forbidding to call static functions from constructors.
There is no reason not to call a static (or in fact a non-static) member function in a constructor (although it is not recommended to call virtual functions).
Related
I have the following piece of code:
How do I call a member function in scope exit.
class A
{
public:
void foo();
void bar();
};
void A::foo()
{
BOOST_SCOPE_EXIT(void)
{
bar(); // Does not compile
}
BOOST_SCOPE_EXIT_END
}
void A::bar() {}
void foo4()
{
A a;
a.foo();
}
Err message
boost_scope_exit.cpp: In static member function ‘static void
A::foo()::boost_se_guard_t_71::boost_se_body()’:
boost_scope_exit.cpp:73:13: error: cannot call member function ‘void
A::bar()’ without object
bar(); // Does not compile
^
How can I call a member function from scope exit.
Found a answer in the boost documentation:
Boost docs
Just search for "Capturing The Object this"
Your code will work if you make bar static (and call A::bar()).
If that's not an option, it looks like you need to capture the this pointer
using the special symbol this_ (note the trailing underscore).
BOOST_SCOPE_EXIT(this_)
{
this_->bar(); // note trailing underscore on this_
}
BOOST_SCOPE_EXIT_END
Now I know that in C++ everything has to be declared before it can be used. But what if I have two functions that reference each other?
For example:
void func1() {
func2();
}
void func2() {
func1();
}
Is it completely impossible to do this?
A forward declaration is exactly what you want:
void func2(); // forward declare func2
void func1() {
func2();
}
void func2() {
func1();
}
The first void func2(); is called a forward declaration. You promise that you will define it according to this prototype eventually.
You need to forward declare func2() to be able to use it in func1():
void func2();
void func1() {
func2();
}
void func2() {
func1();
}
Now at the point where func1() references func2(), func2() has been declared, and at the point where func2() references func1(), func1() will have been declared.
However, calling either one of the two functions will cause an infinite loop, which will result in a stack overflow.
Is that snippet of code impossible without some sort of forward declaration? Yes. Think about it, when the compiler gets here:
void func1() {
func2();
}
He has never seen func2 before, and therefore can't compile it.
Most people create a .h file that contains function declarations so you can avoid this type of thing. For example,
foo.h
void func1();
void func2();
foo.c
#include "foo.h"
void func1() {
func2();
}
void func2() {
func1();
}
You should accept one of the other answers because that's how the language C++ works and there's nothing to do about it, if your concern is that writing lots of forwards is a pain, you should note that several frameworks already provide headers just for the sake of forward declaring stuff so that users don't have too.
This is for convenience when there's really a lot of stuff that is forward declared or there's stuff that need to be declared correctly (in example templates, aliases and also I saw some macro trickery once in a while).
Also generally you have to put declarations and definitions in different files to avoid recompiling where possible and generally to make the project more clear and manageable.
Functions.hpp
void func();
void func2();
Functions.cpp
#include "Functions.hpp"
void func(){
func2();
}
void func2(){
func();
}
user code:
main.cpp
#include "Functions.hpp"
int main(){
func();
return 0;
}
Also note that you have some confusion about "Declaration" and "Forward Declaration".
Actually when you put a function signature in your code your are Declaring it:
int function3(); // function declared
Forward declaration is about telling a class exists without telling anything more about its signature:
class myclass; //forward declaration
//possible declarations using "myclass" forward declaration
int function4(myclass & ref);
int function5(myclass * ref);
Forward declaration is used to keep headers simple and reducing compile time (a lot in certain cases) by moving unneeded details to implementation (.cpp) files.
You can simply place one function inside the other, then expressed as a (usually static) member function of a class, or as a lambda.
This assuming that the top-level calls from elsewhere are always to one of the functions.
Another possibility, with both functions available to the top-level calling code, is to place both functions as (most naturally static) members of a class, where they can be defined inline.
But I think it's more clean to just use the forward declaration.
There isn't really any good reason to avoid it, so a workaround like one of those mentioned above would just make other programmers waste some time scratching their heads – what on Earth is this for?
Amendment: example of the class scope approach:
struct Recursive
{
static void func1() { if( some_condition ) { func2(); } }
static void func2() { if( some_condition ) { func1(); } }
};
Example of the nested functions approach:
void func1()
{
const auto func2 = []{ if( some_condition ){ func1(); } }
if( some_condition ) { func2(); }
}
It's certainly possible with member functions. For example:
class A {
void func1() {
func2();
}
void func2() {
func1();
}
};
It can be more problematic if you need two classes to know about each other but does that answer your question?
Edit: You don't need the member function declarations before their definitions.
How could I make a function only seen by the function that calls it?
define the function I want to hide as private function is not enough, as it could still be seen by other public functions in the class.
Now I use lambda expression to define anonymous function inside function. Is there any better solution?
Aside from using a lambda (which you've rejected), you could implement your function in its own compilation unit, and code the supporting function in an anonymous namespace within that compilation unit.
But that supporting function would be outside the class, so you'd have to pass it all the parameters it needed. That could become unwieldly though no worse than a long lambda capture list.
You can use a function object. For example(you can compile this, even in C++03):
#include <iostream> // only for output
class foo{
int bar(){return 0;} // Only foo can see this
public:
int operator()(){
return bar();
}
};
class baz{
public:
foo do_foo;
};
int main(){
baz a;
std::cout << a.do_foo() << std::endl;
}
the method bar is only visible by a foo.
P.S.: If you need foo to access members of baz, make it a friend.
A simmilar approach to cassiorenan would be to use static class functions and friends.
Something like this:
void Boss();
class Worker {
static void Test(){ return;}
friend void Boss();
};
void Boss(){
Worker::Test();
}
Though why would you want to do this, I don't know.
It is possible to define function inside a function without lambdas. Just define a struct that contains required function. This approach is not much better than using lambda, but at least this is straightforward and works with older compilers too.
int func() {
struct {
int hiddenFunc() {
return 1;
}
} h;
int a = h.hiddenFunc() + h.hiddenFunc();
return a;
}
As a slight variation from cassiorenan's solution, you could use a class containing one public static function (the visible function) and one static private function that could only be called from there. To avoid creation of objects of that class, it is enough to put a private constructor.
EDIT:
Per cassiorenan's comment, I can see that OP really needs methods and not functions. In that case, I would still use a dedicated class in a anonymous namespace to ensure it is not visible from elsewhere (even if my example is single file ...) friend to the class really used. So in below example, bar is the business class that would have a method with an externally hidden implementation (here relay_method), and foo is dedicated to the hidden method called with a pointer to the real object. In real world, the whole anonymous namespace and the implementation of the hidden method should be in the implementation file bar.cpp.
That way, the real implementation function priv_func can only be called from a bar object through bar::relay_method() and foo::bar_func(bar &).
#include <iostream>
class bar;
namespace {
class foo {
private:
static int priv_func(int i) {
return i * i;
}
foo() {}
public:
// only useful if true functions were needed
/* static int pub_func(int i, int j) {
return priv_func(i) + priv_func(j);
}*/
static void bar_func(bar& b);
};
}
class bar {
int x;
int x2;
public:
bar(int i): x(i) {}
void relay_method() {
foo::bar_func(*this);
}
friend class foo;
int getX2() const {
return x2;
}
};
void foo::bar_func(bar& b) {
b.x2 = foo::priv_func(b.x);
}
using namespace std;
int main() {
/* int i = foo::pub_func(3,4);
cout << i << endl;
// foo::priv_func(2); error access to private member of class foo
// foo f; */
bar b(2);
b.relay_method();
cout << b.getX2() << endl;
return 0;
}
I can't understand what's happening...
Suppose that I have the following code:
// main.cpp
#include "some_header.h"
void bar();
int main()
{
foo();
bar();
}
// file.cpp
#include "some_header.h"
void bar()
{
foo();
}
// some_header.h
#include "foo.h"
inline
void foo()
{
static Foo instance;
}
// foo.h
#include <iostream>
class Foo
{
public:
Foo() { std::cout << "Foo::Foo() \n"; }
~Foo() { std::cout << "Foo::~Foo() \n"; }
};
Output
Foo::Foo()
Foo::~Foo()
The question is: why there's no second "Foo::Foo()" in the output? I think that it should be here because each translation unit (in my case main.cpp and file.cpp) should have its own Foo object (because of static keyword). Am I wrong? Can somebody quote the standard, please?
If i move the definition of Foo object from the function like this
// some_header.h
#include "foo.h"
static Foo instance;
inline
void foo()
{
}
the output will be
Foo::Foo()
Foo::Foo()
Foo::~Foo()
Foo::~Foo()
Is it inline magic or am I missing smth more fundamental?
What I need to do - I need to add boost::mutex object in some function for my header-only library to synchronize some WinAPI function calls like this:
inline
void some_func()
{
static boost::mutex sync;
boost::lock_guard<boost::mutex> lock(sync);
// Call some WinAPI function
}
How can I do it?
MSVC-11.0.
static is a heavily overloaded keyword in C++. At namespace scope, it means "entity has internal linkage, so every translation unit will have its own copy." At function scope, it means "there is only one such entity for the function and it persists across function calls."
So in your case, the funcion foo() simply has one object Foo instance with local scope, but global lifetime.
As for your mutex question, I can't see anything wrong with doing just what you posted in the question. some_func() will have a single instance of the mutex, and all calls to some_fucn() will share that one instance (and since C++11, it will be correctly and thread-safely initialised by the first such call). I'd say that's exactly what you need.
I have
class Foo
class Bar
Now, I want
Foo* Foo::singleton = new Foo();
Bar* Bar::singleton = new Bar();
to both initialize before
int main()
is called.
Furthermore, I want
Foo::singleton
to initialize before
Bar::singleton
Is there anyway I can ensure that?
Thanks!
Global variables (like the singletons) that are defined in the same translation unit are initialized in the order in which they are defined. So put the definition of both singletons in the same source file, in the correct order.
If they would be defined in different source files the order in which they are initialized would be unspecified (the "static initialization order fiasco").
See also Static variables initialisation order
For gcc use init_priority:
http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
Works across different translation units. So your code would read:
Foo* Foo::singleton __attribute__ ((init_priority (2000))) = new Foo();
Bar* Bar::singleton __attribute__ ((init_priority (3000))) = new Bar();
I don't have gcc handy right now so I can't verify this, but I have used it before.
The other simpler and more portable solution is to avoid static initialization, and explicitly create the singletons in order at some well defined place within main.
// Nothing in static area
void main(void)
{
// Init singletons in explicit order
{
Foo* Foo::singleton = new Foo();
Bar* Bar::singleton = new Bar();
}
// Start program execution
...
}
Remember, things will get just as gnarly with singletons on the way out of the program as well, so its often better to make it explicit.
#include <iostream>
class Foo {
public:
static Foo *singleton ()
{
if (foo == NULL)
foo = new Foo;
return foo;
}
private:
Foo ()
{
std::cout << "Foo()\n";
}
static Foo *foo;
};
Foo *Foo::foo = NULL;
Foo *singleton = Foo::singleton ();
int
main ()
{
std::cout << "main()\n";
return 0;
}
Output:
Foo()
main()
In a nutshell:
// smooth.cpp
#include "foo.h"
#include "bar.h"
Foo* Foo::singleton = new Foo();
Bar* Bar::singleton = new Bar();
A nice syntax, to avoid worrying about that:
Foo& Foo::singleton()
{
static Foo Singleton;
return Singleton;
}
The good thing about this syntax, is that the singleton is initialized at the first call of the method, thus you don't have to worry (usually) when it happens, since when calling the method to access it you get it anyway :)