Global class variable vs pointer in c++ [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Lets assume I have the following class:
class A
{
public:
A() {}
};
I need to declare a global instance of class A (required by spec.), what works better?
A a; // is the constructor even called here?
or
A* pa; // and allocate later a new instance
Thanks in advance

"A a; - is the constructor even called here?" - yes, the constructor is called.
"* pa; - and allocate later a new instance" - if you actually assign something to this pointer variable before using it, then it can work. But do you?
In general I'd say that the need for global variables indicate a flaw in the design. But if you really have to have them, then make sure they are constructed before you use them.

If A a is used, there would not be a need to release memory allocated to a. When the main() function exits, the destructor for A will be automatically called.
If A *pa is used, ideally pa should be explicitly deleted at some point in the code with delete pa and care should be taken to not use pa after it has been deleted.

Related

Template class buffer destructor c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a template class Array that has a buffer type vector.
template <typename T>
class Array
{
protected:
std::vector<T> buffer;
......
}
I want to implement the destructor ~Array(); for this buffer. Any ideas on how to do it?
The default destructor is already releasing the memory of vector, you don't need to define one here.
If you want to free memory of the vector explicitly, then try swap technique whenever you want:
std::vector<T>().swap(buffer);
Any ideas on how to do it?
It depends completely on what you've designed the class and its destructor to do.
The best option, when ever it does what is needed, is to not have a user declared destructor at all, but the implicitly generated one instead. In other words, follow the rule of 0 when possible.
I want to delete the allocated memory of the buffer
All member variables are destroyed automatically. The destructor of the vector deallocates its internal buffer. There is no need for a custom destructor here.

How default constructor knows where to initialize the default values of the data member in memory [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
From book "The first hidden argument to the constructor is the this pointer"
Now when we write like
classname object;
Is it like first memory for the object is created and address of the object is pass to default constructor so that it can initializes the values of the class.
If this is the concept for object how memory is created, is it created by the OS ?
It depends on where you write your definition:
If you define your object at global scope the linker will figure out where to place the object in the program’s data area and make sure there is enough space. The same is true for all static objects, independent of whether they are static class members or function local statics.
If you define your object as a local object in a function it will be placed on the stack. The calling conventions on the system in use will arrange for enough space on the stack (assuming there is enough space on the stack to start with; otherwise you’d get a stack overflow).
If your definition is actually a member declaration, space for the object will be made in the containing object and the new object will be placed there.
Just for completeness, when using a new expression the space is allocated on the heap and the object is places there.
Another case are thread local objects which are placed somewhere on the thread’s stack.
Note that the placement of objects applies to all constructors: the only significance of the default constructor is that you don’t pass any arguments when constructing the object.
As John mentioned in the comments, there is no explicit information in the Standard on how the memory is allocated/managed. However, assuming that no compiler optimizations take place and that you are creating an object on the stack... then this will likely happen.
Given:
void f()
{
foo x;
}
The compiler will produce something like:
void f()
{
char foo_buffer[sizeof(foo)];
new (&foo_buffer) foo()
reinterpret_cast<foo*>(foo_buffer)->~foo();
}
The space for a foo instance is reserved on the stack, then the constructor is called on that space. At the end of the scope, the destructor is called.
When an object is created, the os will Create the space.when the object is created the os automatically calls the default constructor .

How to initialize array of pointers to classes? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
given class (for example in name of X) , I want to allocate array like that:
X** array=new X*[20];
Let's look about the following function:
void Func(){
X** array=new X*[2];
X[0]=& X(5);
X[1]=& X(3);
}
Is it OK to do it like that or that I must to do it with new?
The thing is, when you do something like this :
X foo(5);
X[0] = &foo;
(wich i suppose is what you want to say)
X[0] will take the adress of foo, wich is a local variable who will only exist in the scope of your function. And if i do not tell bullshit, does not compile. (-fpermissive)
So after the last instruction of your function, the usage of this pointer will be Undefined
You can't be sure after any allocation that the content of your data is equal to nullptr (if not initialise yet). Initialisation syntax have way different behavior depending language, compiler, stars position etc (just kidding for the last one) so make sure to read the documentation about it.
However you can be sure to init something with null Value by using a zero-initialisation. Link here
If you don't want to dynamicly allocate your array of pointer make sure that those pointer still valid during the lifetime of your object
Another solution could be to dynamicly allocate them.
X[0] = new X(5);

Objects of a class derived from an abstract class should be in free store? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to wrap my head around what seems to be strange to me in TC++PL. It is about allocation of a class derived from an abstract class.
Since we don't know anything about the representation of an abstract type, we must allocate objects on the free store and access them through references and pointers.
Why free store? As you already know, a class derived from an abstract class can be allocated like any other local variables. I have no idea what exactly TC++PL tries to convey in this sentence.
In my opinion it is an incorrect statement. For example if you have an abstract base class B and derived (non-abstract) class D then you can write
D d;
B &b = d;
that is object of type D is created in stack provided that this code is in some function.
They mean that if you want to use some abstract class without knowing what concrete type that is, you must use dynamic allocation for it, i.e that you cannot write abstract_class A = concrete_class B;

Deleting multiple pointers with single delete operator [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
For deleting and an array of element we use delete[].
Is it possible to delete the pointers the way I am doing below?
ClassA* object = new ClassA();
ClassA* pointer1 = object;
ClassA* object2 = new ClassA();
ClassA* pointer2 = object2;
delete pointer1,pointer2;
Why its not possible to use delete this way?
[Edit]
Can I put it like, what are the drawbacks due to which the above delete has not been implemented?
It's not possible, because there is no provision for it in the C++ language definition. I'm not sure there is any "good" answer to why the language doesn't support a list of items for delete, except for the fact that it's simpler to not do that.
You need to write one delete for each variable. Of course, if you have many pointerX, then you probably should be using an array instead, and use a loop to delete the objects.
Edit: Of course, if you are calling delete in many places in your code, you are probably doing something wrong - or at least, you are not following the RAII principles very well. It's of course necessary to learn/understand dynamic allocation to have full understanding of the language, but you should really avoid calling both new and delete in your own code - let someone else sort that out (or write classes that do "the right thing")
It is not working this way. delete is a command for a single pointer. You can put the pointers in a structure (e.g. array) or a container (e.g. using a vector container class) and delete for each one of them by iterating the structure/container.