Example:
struct Foo { Foo() { printf("foo\n"); } };
static Foo foo;
__attribute__((constructor)) static void _bar() { printf("bar\n"); }
Is it deterministic wether foo or bar is printed first?
(I hope and would expect that constructors of static objects are always executed first but not sure and GCCs doc about the constructor attribute doesn't say anything about it.)
foo will be printed first, as the objects are initialized in the order of their declarations. Run and see:
Ideone online demo
By the way, __attribute__((constructor)) is not Standard C++. It is GCC's extension. So the behavior of your program depends on how GCC has defined it. In short, it is implementation-defined, according to it foo is printed first.
The doc says,
The constructor attribute causes the function to be called automatically before execution enters main (). Similarly, the destructor attribute causes the function to be called automatically after main () has completed or exit () has been called. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program.
You may provide an optional integer priority to control the order in which constructor and destructor functions are run. A constructor with a smaller priority number runs before a constructor with a larger priority number; the opposite relationship holds for destructors. So, if you have a constructor that allocates a resource and a destructor that deallocates the same resource, both functions typically have the same priority. The priorities for constructor and destructor functions are the same as those specified for namespace-scope C++ objects (see C++ Attributes).
I think the text in bold implies, the objects are initialized in the order of their declarations, as I said before, which is pretty much confirmed by online demo also.
I guess you would also like to read this:
7.7 C++-Specific Variable, Function, and Type Attributes
If you want to control/alter the initialization order, you can use init_priority attribute, providing priority. Taken from the page:
Some_Class A __attribute__ ((init_priority (2000)));
Some_Class B __attribute__ ((init_priority (543)));
Here, B is initialized before A.
It isn't defined by the standard, but here is my experiment https://github.com/SanSanch5/static-initialization-order-example
The output on gcc-9:
CFoo constructed
dll constructor
CBaz constructed
CBar constructed
foo
dll destructor
CBar destructed
CBaz destructed
CFoo destructed
The output on clang-12:
CFoo constructed
dll constructor
CBaz constructed
CBar constructed
foo
CBar destructed
dll destructor
CBaz destructed
CFoo destructed
So, the dll constructor is being called before static initialization, but as you can see, the destruction is slightly different on gcc and clang. But initializing a static object inside a dll constructor experimentally proves its destruction after the other static objects. But it's non-standard so not reliable.
Related
I came across this where one of the user comment says:
A constructor cannot be called, it is not a function. It is invoked automatically when a new object is created.
My question is that is the above comment true/correct? If yes, then why isn't a constructor considered a function and why can't we call it?
Formally in the C++ Standard it is (along with several others) a special member function so yes it is a function, but it is a special function and not all of the normal rules apply.
There is no syntax to write code that calls a constructor directly or forming a function pointer to it. The Standard specifically says "Constructors do not have names."
The compiler will automatically call a constructor when an object is created. The compiler will also automatically call constructors for subobjects (bases and members) of a class object. "Delegating constructors" are sort-of a degenerate case of initialization of subobjects (In formal algebra, we say that any set is a subset of itself, and say "strict" subset when we mean a subset that is not the entire set).
There are a variety of ways to create an object and some of them look like a function call, but that's actually a cast and results in creation of a new object, on which the constructor is called implicitly by the compiler. There's also placement-new syntax which doesn't do very much besides causing the compiler to implicitly call the constructor -- but even there a brand new object is being created.
One important way in which the compiler's implicit call to a constructor differs from an explicit function call found in user code is that the implicit call occurs within an implicit try/catch scope that will result in destruction of subobjects if an exception occurs. A direct call to the constructor, if one were possible, wouldn't have such extra behavior.
When I was using an "union" of objects where I had to manage the destruction and construction of the members of the union, I was able to call the constructor like this using the "new operator":
new(&variable) NameOfTheClass
#include <iostream>
class A {
public: A() {std::cout << "constructor called for pointer " << this << std::endl;}
};
int main() {
A a;
new(&a) A; //Should call a second time the constructor
}
The quoted comment is incorrect. A constructor is a special member function. And it can be implicitly called by the compiler at the time of object creation.
For example,
struct A
{
};
int main()
{
//----v----->note the absence of parenthesis like when we call a function
A a; //creates object of type A by implicitly calling the default constructor
}
These are some of the special(things to be noted) things about constructors:
They don't have return types.
They are automatically synthesized by the compiler given certain conditions are satisfied.
They are implicitly called by the compiler at the time of object creation.
1- Yes, the constructor is a member function with a specific signature having the same name as for Class.
2- The default constructor is called implicitly when it is not called explicitly. But it can be called explicitly using "super()" in Java and "Base()" in C# in respective child classes.
why does creation of an object needs a constructor?
Even if I don't define a constructor a default constructor is generated ..but why a constructor necessary?
why can't objects be created without a constructor?
This is more of a discussion on terminology than a real argument about the behavior. As you mention, in some cases there is nothing to be done during construction, so there should be no need for a constructor, right? Well, there is the concept of a trivial-constructor which is a constructor that does not do anything at all. For the sake of the standard document, it is easier to treat everything as having a (possibly trivial) constructor than to have to provide all the cases and exceptions in all places where it currently just states 'constructor'.
Consider that every use of 'constructor' would have to be replaced by 'constructor or nothing if the type does not have any virtual functions or bases and no members that require the generation of a constructor'.
This is the same reason why all virtual functions are called overrider even the first one in the hierarchy that by definition does not override anything. This form of generalization makes the language slightly easier to interpret, although not too many people will claim that section 8.5 on initialization is simple...
Also note that, while all user defined types by definition have a constructor, the constructor is not required for the creation of objects. In particular for objects with trivial-constructor the lifetime starts when the memory for the object is allocated (the standard, knowing that trivial means nothing to be done does not even go through the hop of requiring that the constructor is run in that case.
3.8 [basic.life]/1
The lifetime of an object is a runtime property of the object. An object is said to have non-trivial initialization if it is of a class or aggregate type and it or one of its members is initialized by a constructor other than a trivial default constructor. [ Note: initialization by a trivial copy/move constructor is non-trivial initialization. — end note ] The lifetime of an object of type T begins when:
-- storage with the proper alignment and size for type T is obtained, and
-- if the object has non-trivial initialization, its initialization is complete.
That second bullet used to read (C++03): if T is a class type with a non-trivial constructor (12.1), the constructor call has completed. Which more clearly stated that the constructor need not be executed. But the new wording expresses the intent in basically the same way. Only if the object has non-trivial initialization, the initialization needs to complete. For objects with trivial-constructor (trivial initialization) allocating the storage creates the object. Where does it matter?
struct T { int x; }; // implicitly defined trivial-constructor
T *p = static_cast<T*>(malloc(sizeof *p));
// *p is alive at this point, no need to do
T *q;
{ void *tmp = malloc(sizeof T);
q = new (tmp) T; // call constructor
}
In a way, this is a slightly philosophical question. You can think of a constructor as a subroutine that turns some uninitialized memory into an object. Or you can think of it as a language feature that makes initialization easier to follow, write, and understand. You could even answer the question circularly: why does creation of an object needs a constructor? Because that's what creation of an object is, in a sense. If you don't have a constructor, what you're creating isn't an object.
It may be that a particular constructor does nothing, but that's an implementation detail of that class. The fact that every class has a constructor means that the class encapsulates what initialization is necessary: to use the class safely, you don't need to know whether the constructor does anything. In fact, in the presence of inheritance, vtables, debug-tracking, and other compiler features, you might not even know whether the constructor does anything. (C++ complicates this slightly by calling some classes POD types, but the encapsulation holds as long as you don't need to know that something is of POD type.)
The invocation of a constructor defines the point at which an object is created. In terms of language semantics, when the constructor finishes, the constructed object exists: before that, the object does not exist, and it is an error to use it as if it did. This is why construction order (that is, the order that member object and base class sub-object constructors are called) is so important in C++ and similar languages: if your constructor can throw an exception, it's necessary to destroy exactly those objects that have been constructed.
To end up with a working program, the programmer, anyone who tries to understand the source code, the compiler and linker, the runtime library, and any other compilation tools, all need to have a shared idea of what the program means: the semantics of the program. Agreeing on the lifetime of an object—when the compiler can run extra code to help create it, and when you can safely use it—is actually a big part of this agreement. Constructors and destructors are part of defining this lifetime. Even if they happen to be empty sometimes, they provide a way for us to agree when an object is valid, thus making it easier (possible) to specify and understand the language.
Say you have a simple class :
class Foo
{
int bar;
}
What is the value of bar exactly? Maybe you don't care when your object gets its memory allocated, but the machine running your program needs to give it some value. That's what the constructor is for : initializing class members to some value.
Constructor is necessary to call the constructors on class members, except built-in types see
Parametrized Constructors can take arguments. For example:
class example
{
int p, q;
public:
example();
example(int a, int b); //parameterized constructor
};
example :: example()
{
}
example :: example(int a, int b)
{
p = a;
q = b;
}
When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly. The method of calling the constructor implicitly is also called the shorthand method.
example e = example(0, 50); //explicit call
example e(0, 50); //implicit call
This is particularly useful to provide initial values to the object.
Also you will find important stuff on this page :
http://en.wikipedia.org/wiki/Constructor_%28object-oriented_programming%29
I have some problems with destructor, in next code:
#include <stdlib.h>
#include <cstdio>
class Foo2
{
public:
Foo2() { printf("foo2 const\n"); }
~Foo2()
{
printf("foo2 dest\n"); // <--- wasn't called for bionic libc
}
};
static Foo2& GetFoo2()
{
static Foo2 foo2;
printf ("return foo2\n");
return foo2;
}
class Foo1
{
public:
Foo1() { printf("foo1 const\n"); }
~Foo1()
{
printf("foo1 dest\n");
GetFoo2();
}
};
int main( int argc, const char* argv[] )
{
printf("main 1 \n");
static Foo1 anotherFoo;
printf("main 2 \n");
}
Why destructor for foo2 wasn't called for bionic and was for glibc?
EDIT
Output for bionic:
main 1
foo1 const
main 2
foo1 dest
foo2 const
return foo2
Debug info:
(gdb) break 22
Breakpoint 1 at 0x8048858: file test.C, line 22.
(gdb) info breakpoints
Num Type Disp Enb Address What
1 breakpoint keep y 0x08048858 in Foo2::~Foo2() at test.C:22
(gdb) cont
[ exited with code 0]
I think your code has undefined behavior, although the standard
isn't really clear about it (or I can't find it in the
standard). Your code constructs a new static object in the
destructor of a static object. The standard doesn't address
this case, but:
It does say that destructors must be called in the reverse
order of construction. In your case, this would imply that the
static object in GetFoo2 must be destructed before it was
constructed, which is self-contradictory.
The text in §3.6/3 describes the sequencing of destructors
and functions registered with atexit. The requirements are
such that the same registration mechanism must be used for each.
And calling atexit once you've called exit (or returned from
main) is undefined behavior.
There's also §3.6/2, which says that "If a function contains
a block-scope object of static or thread storage duration
that has been destroyed and the function is called during the
destruction of an object with static or thread storage
duration, the program has undefined behavior if the flow of
control passes through the definition of the previously
destroyed blockscope object." This sentence talks about alread
destroyed objects, but it doesn't take much imagination to think
that the absense of "not yet constructed" objects is just an
oversight.
In the end, I'd say that my first point above is conclusive with
regards to intent. In §1.3.24, there is a note (non normative,
but indicative of intent) "Undefined behavior may be expected
when this International Standard omits any explicit definition of
behavior or when a program uses an erroneous construct or
erroneous data." In this case, the only description of the
required behavior is impossible (since you cannot destruct an
object before it was constructed), and the standard says nothing
about how this should be resolved.
All the instances I see in this code are static.
By consequence their destructor is called at the end of the executable, after main is finished.
if the destructor wasn't called then it was a bug.
static object will be destroyed when program exists. put a break point at ~Foo2(), you will see it or write log to a file should help you diagnose it. If really not called then it's a compiler bug.
And it's fun to upload a pic to answer a question.
C++11 3.6.3/1: Destructors for initialized objects [...] with static storage duration are called as a result of returning from main
At the point at which the program returns from main, anotherFoo has been initialised; but foo2 hasn't, since it is not initialised until the first call to GetFoo2 during the destruction of anotherFoo. Therefore, a strict interpretation of the rules would imply that its destructor should not be called.
Having a simple class:
class A {
public:
A() {}
void set(int value) { value_ = value; }
private:
int value_;
};
and its global instance:
A a;
Is it OK to call method set on a not yet constructed object a? That can happen when for example a.set(123) is called from a constructor of another global object in another translation unit.
Will the value in the object a set by calling a.set(123) remain when the non-parametric and empty constructor of A is later called for object a?
Is it ok to call method set on a not yet constructed object a?
No. You may not call member functions for an object that has not yet begun construction.
(Since the answer is no, your second question requires no answer.)
If you may need to access this global instance from multiple translation units during dynamic initialization, you can use the Meyers singleton technique:
A& global_a()
{
static A a;
return a;
}
a will be initialized when global_a() is first called. Note that in a multithreaded program you may need to concern yourself with synchronization of the initialization.
When you write
A a;
a is a constructed object now. In case A is a then A default constructor was already been called
If in 1) you mean it's ok to call set in the constructor, then yes, that's fine because it isn't a virtual method. You cannot call a virtual method in the constructor.
As for 2), what you're asking isn't really clear. The constructor is only called once (although there are ways around that sort of thing, but don't do them) and that is when the object is first created. You can't call the constructor on a a second time so the question doesn't really make sense.
class Foo {
public:
Foo() { Foo(1)}
Foo(int x, int y = 0):i(x) {}
private:
int i;
}
Can anybody give me some reasonas about can I do this? If not why?
Because the language specification doesn't allow it. Just the way the language is. Very annoying if you're used to Java or other languages that allow it. However, you get used to it after a while. All languages have their quirks, this is just one of C++'s. I'm sure the writers of the specs have their reasons.
Best way around this I've found is to make a common initialization function and have both constructors call that.
Something like this:
class Foo {
public:
Foo() {initialize(1);}
Foo(int nX) { initialize(nx); }
private:
void initialize(int nx) { x=nx; }
int x;
};
It's a language design choice.
A constructor is a one time (per-object) operation that creates a new object in uninitialized memory. Only one constructor can be called for an object, once it has completed the object's lifetime begins and no other constructor can be called or resumed on that object.
At the other end of its life a destructor can only (validly) be called once per object and as soon as the destructor is entered the object's lifetime is over.
A prinicipal reason for this is to make explicit when an object destructor will be run and what state it can expect the object to be in.
If a class constructor completes successfully then it's destructor will be called, otherwise the object's lifetime has never begun and the destructor will not be called. This guarantee can be important when an object acquires resources in its constructor that need to be released in its destructor. If the resource acquisition fails then the constructor will usually be made to fail; if the destructor ran anyway it might attempt to release an resource that had never been successfully acquired.
If you allow constructors to call each other it may not be clear if a calling or a called constructor is responsible for the resource. For example, if the calling constructor fails after the called constructor returns, should the destructor run? The called constructor may have acquired something that needs releasing or perhaps that was what caused the calling construtor to fail and the destructor shouldn't be called because the resource handle was never valid.
For simplicity of the destruction rules it is simpler if each object is created by a single constructor and - if created successfully - destroyed by a single destructor.
Note that in C++11 a constructor will be able delegate to a different constructor, but there are limitations that don't really relax the principal of one construction per object. (The prinicipal constructor can forward to a target constructor, but if it does it must not name anything else (base classes or members) in its initializer list. These will be initialized by the target constructor, once the target constructor returns the body of the prinicipal constructor will complete (further initialization). It is not possible to re-construct any bases or members, although it allows you to share constructor code between constuctors.)
You cant do this. See section 10.3: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.3. You can try to do it but doing so will construct a new temp object (not this) and be destroyed once control moves on.
What you can do however is to create a private function that initializes variables, one that your default constructor or a parameterized constructor can both call.
There is a really hideous hack I have seen used to call another ctor. It uses the placement new operation on the this pointer. erk
Like this:
Class::Class(int x) : x_(x) {}
Class::Class() {
new (this) Class(0);
}
Class::Class(const Class &other) : x_(other.x_) {}
Class& operator=(const Class &other) {
new (this) Class(other);
return *this;
}
Note that I am not recommending this, and I don't know what horrible effects it might have on C++ structures like virtual base classes, etc. But I expect that there are some.
Although as per standards vendors are free to implement data binding in their own ways, if we consider the most popular implementation: this pointer, we can see a reason why this can't be implemented.
Assume you have a class:
class A
{
public:
A(){}
A(int a){}
} ;
With the this pointer implementation, this class would look something like:
class A
{
public:
A(A *this){}
A(A *this,int a){}
} ;
Typically you would create objects like this:
A ob ;
Now when compiler sees this, it allocates memory for this and passes the address of this allocated memory block to the constructor of A which then constructs the object. It would try to do the same every time for each constructor called.
Now when you try calling a constructor within another constructor, instead of allocating new memory the compiler should pass the current objects this. Hence inconsistency!
Then another reason which i see is that even though you might want to call a constructor within another, u would still want a constructor to call default constructors for all the objects within the class. Now if one constructor were to call another, the default construction should happen for the first constructor and not for the subsequent one's. Implementing this behavior means that there would be several permutations which need to be handled. If not, then degraded performance as each constructor would default construct all the objects enclosed.
This is what i can think of as possible reasons for this behavior and do not have any standards to support.