问题
I found some answers for this question regarding java but nothing specifically regarding c++. So I've read in Java the object is first created and then the constructor is called. I was wondering if this was the same process for c++? Also, if this is the case, then what's the point of having a default constructor at all? Is it for inheritance purposes?
回答1:
"Object creation" means different things in different languages. But in C++ the most salient question is "when does the object lifetime begin". When an object's lifetime has begun, that means that when it later ends (you delete it, or if it is a stack object, then when it goes out of scope), the destructor will be called.
If the object's lifetime did not formally begin, then if it goes out of scope later, the destructor will not be called.
C++ resolves this as follows:
- When you make an object, say of class type, by invoking a constructor, first the memory is allocated, then the constructor runs.
- When the constructor runs to completion, then the lifetime has begun, and the destructor will be called when it ends. After the destructor finishes, the memory will be freed.
- If the constructor aborts, say, by throwing an exception, then the destructor for that object will not be called. The memory will still be freed, however.
For more info on object lifetimes you might want to look at e.g. this question, or better, at the standard / a good text book.
The basic idea is that, in C++, we try to minimize the window of time between when the memory has been allocated and when it is initialized -- or rather, the language itself promotes the idea that "resource acquisition is initialization" and makes it un-idiomatic to acquire memory without also giving it a type and initializing it. When typically writing code, e.g. if you have a variable of type A, you can think of it as "This refers to a block of memory for an A, where a constructor for A successfully ran to completion." You don't normally have to consider the possibility that "this is a block of memory the size of an A, but the constructor failed and now its an uninitialized / partially initialized headless blob."
回答2:
It depends on what you mean by "created". Obviously memory should be allocated before object can be created.
But officially, object is not created (its lifetime is not started) until after constructor finishes execution. If constructor did not execute completely (exception happened, for example), object is considered never existing in first place. For example destructor for this object will not be called (as it would for any existing object)
When you enter constructor body, you can be sure that members are create (either by default constructors or whatever was passed in constructor initializer list; usual language rules for variable initialization applies: initial values of scalar variables are undefined).
When you consider inheritance, it is even more complex. When you enter constructor body, ancestors parts are already existing objects: their constructor had finished, and even if children would not be able to construct itself properly, their destructors will be called.
回答3:
Neither.
The process of object creation includes a constructor call.
The point of having a default constructor is to allow this part of the object creation process to be a no-op. What else would it be?
回答4:
Here's the sequence: first, memory is allocated. Then any base class constructors are called. Finally the class constructor is called.
You don't actually need a default constructor if you'll always create your objects with a parameter list.
回答5:
You seem to be confusing terms but I'll try to define some (unofficial) terms that should clarify this issue:
- Allocation
This is the step where memory is allocated for the object. - Initialization
This is the step where the language related object properties are "set". The vTable and any other "language implementation" related operations are done. - Construction
Now that an object is allocated and initialized, the constructor is being executed. Whether the default constructor is used or not depends on how the object was created.
You can consider an object created after the 3rd step.
回答6:
Also, if this is the case, then what's the point of having a default constructor at all?
The point of "Default Constructor" is to tell the program how objects with no parameters should be built, in other words - what is the "default" state of an Object.
for example, the default state of std::unique_ptr is to point to null with no costume deleter.
The default state of a string is an empty string with the size of 0.
The default state of a vector is an empty vector with the size of 0.
The default state of T is the one specified by the constructor T().
回答7:
Think that constructor has to be called after object's creation due to resource allocation issues. An object is no more than a structure with functions pointers (members function) and member variables (attributes). An error would occur if the constructor sets up any of these values before they are allocated in memory.
For example, your constructor stores an int value in a member variable of your object, but your object's member variables haven't been allocated, so the value cannot be stored successfully.
Regards!
回答8:
Yes, the object's memory is first allocated, then the constructor called to actually construct the content. A bit like building a house, you first purchase [or otherwise legally get permission] the land (memory) to build it on, then start building. If you do it the other way around, you're likely to get into trouble.
A default constructor is used when your object needs to be constructed with no parameters. In some cases, this doesn't make any sense at all, but default constructors are used for example in the std::vector - since a std::vector<myclass> will be implemented as an array of objects, and if you grow it [using push_back], the size will double (or something like it), and the objects at the back of the vector that hasn't been used will be default constructed.
All objects need to be constructed after creation (even if you don't declare one, in which case you get an empty constructor, and if the compiler is clever it will not call the constructor because it doesn't do anything)
回答9:
The term "default constructor" just means a constructor that needs no parameters, such that it can be used by-default. For example:
struct MyObject {
MyObject() { ... } // default constructor
MyObject(int) { ... } // some other non-default constructor
};
int main()
{
MyObject x; // default constructor is called since you didn't give
// any explicit parameters.
MyObject x2(5); // A non-default constructor is called.
}
Note that the term "default" doesn't mean that you haven't defined it. The default constructor may be provided by you or it may be automatically generated in certain situations. You even have the case of the defaulted default constructor:
struct MyObject {
MyObject() = default; // defaulted default constructor
};
Here, you've told the compiler to generate a default constructor using the default implementation.
Regardless of whether it is a default constructor or not, the object has been constructed as much as automatically possible before the constructor body is executed. This means the memory has been allocated to store the object, any base classes have been constructed, and any members have been constructed. The object also has taken the type identity of the class being constructed for purposes of RTTI and virtual function calls.
来源:https://stackoverflow.com/questions/34400042/in-c-are-constructors-called-before-or-after-object-creation