Dynamic and static variable

hi friends ,i am a beginner in c++ and i have some questions and i will be thankful if you help me to find its answers
1-a)a dynamic local variable has been declared in a function (method)
as below:
Work * p = new Work (p);

at the end of the function will this variable be released and erased (without making a call to its destroyer)?
b)if so: and if we call the destructor what will change?
------
2-And if we declare in its place a static variable:
Work p;

at the end of the function will this variable be released and erased?

-------------------------------------------------- -------------------------------------------------- ------------------
3-why do we prefer to work with a dynamic variable (and not a static variable) as a local variable?
m aAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Fabrice LambertFabrice LambertCommented:
To answer your questions:
1-a) The variable will hold that address of a dynamically alocated memory area.
The variable will be destroyed automatically, but the alocated memory won't be released, unless you explicitly delete it.

1-B) You have to use the delete operator on dynamically allocated variables, it will call the destructor. You don't call destructors by yourself.

2) This is an "automatic" variable, wich mean it will be automatically destroyed when it goes out of scope.

3) It is better to work with automatic variables, and dynamic allocation should not be handled by yourself, especially as a beginner since dynamic allocation when not properly managed is a major source of troubles.
Now, C++ offer tools: Smart pointers (std::unique_ptr, std::shared_ptr or std::weak_ptr)  that will manage memory for you safely.

Consider the following code:
int main()
{
    int* first = new int;
    int* second = new int;
    delete second;
    delete first;
    return EXIT_SUCESS;
}

Open in new window

This is buggy.
The new operator can throw an exception.
If the allocation of "second" fail, the program terminate immedialty, and memory allocated by "first" is never released.
Either use exception handlers:
int main()
{
    int* first = new int;
    try
    {
        int* second = new int;
    }
    catch(std::exception& e)
    {
        delete first;
        return EXIT_FAILURE;
    }
    delete second;
    delete first;
    return EXIT_SUCCESS;
}[/

Open in new window

This is better, but this is also more work, a source code harder to read, and more error prone.
Or use smart pointers:
int main()
{
    std::unique_ptr<int> first = std::make_unique<int>();
    std::unique_ptr<int> second = std::make_unique<int>()
    return EXIT_SUCCESS
}

Open in new window

Not only this does not require to delete memory explicitly, but memory will be properly deleted in case of troubles. Plus the code is shorter and easyer to read.
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
phoffricCommented:
>> Work * p = new Work (p);
 This statement is written incorrectly .
 See below link for code example on how to write it correctly.
http://www.cplusplus.com/reference/new/operator%20new/
0
phoffricCommented:
>> if we call the destructor what will change?
The pointer that points to the destructed object will still have an address to an invalid object.

Also, the following is from this link:
https://stackoverflow.com/questions/14187006/is-calling-destructor-manually-always-a-sign-of-bad-design

To understand why and when you need to call destructors explicitly, let's look at what happening with "new" and "delete".

To created an object dynamically,  T* t = new T; under the hood: 1. sizeof(T) memory is allocated. 2. T's constructor is called to initialize the allocated memory. The operator new does two things: allocation and initialization.

To destroy the object delete t; under the hood: 1. T's destructor is called. 2. memory allocated for that object is released. the operator delete also does two things: destruction and deallocation.

One writes the constructor to do initialization, and destructor to do destruction. When you explicitly call the destructor, only the destruction is done, but not the deallocation.

A legitimate use of explicitly calling destructor, therefore, could be, "I only want to destruct the object, but I don't (or can't) release the memory allocation (yet)."

A common example of this, is pre-allocating memory for a pool of certain objects which otherwise have to be allocated dynamically.

When creating a new object, you get the chunk of memory from the pre-allocated pool and do a "placement new". After done with the object, you may want to explicitly call the destructor to finish the cleanup work, if any. But you won't actually deallocate the memory, as the operator delete would have done. Instead, you return the chunk to the pool for reuse.
1
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

phoffricCommented:
>> why do we prefer to work with a dynamic variable (and not a static variable) as a local variable?
 
 If you do not know the dimensions of an array or matrix that you need to use as a local variable , then you can use a dynamic variable to allocate the right amount of memory . The dimensions might be passed then as arguments to assumption , or maybe computed within the function .
0
Fabrice LambertFabrice LambertCommented:
 If you do not know the dimensions of an array or matrix that you need to use as a local variable , then you can use a dynamic variable to allocate the right amount of memory . The dimensions might be passed then as arguments to assumption , or maybe computed within the function .
What do you think std::vector are for ?
0
phoffricCommented:
I thought about mentioning vector, but chose not to. In the OP: "i am a beginner in c++" and the question is partly about benefits of dynamic and new. Based on the OP, I didn't want to introduce a new topic that might confuse the author.
0
Fabrice LambertFabrice LambertCommented:
@phoffric:
Honestly, vectors as easy to manipulate as C-style array, plus they provide many benefits:
- Manage memory for you, so you can focus on application logic rather than system managment.
- Auto expand.
- Thread safe.
- Embeded size.
- Ranged for loop enabled.
- Iterators enabled.
- STL algorythms enabled ect ect ...

Don't be scared by the template declaration syntax, vectors are variables like any other.
1
phoffricCommented:
@fabrice,
I strongly recommend that you stick to the OP's question and not introduce non beginner topics such as iterators, threads, etc. !!
0
m aAuthor Commented:
@Fabrice Lambert @phoffric,
Thanks for your clarifications, :)
and in fact , i have an idea about vectors and all that ,but i had a little confusion about destructors  and now it's  gone of course ;) .
0
Fabrice LambertFabrice LambertCommented:
@phoffric:
I admit that iterators and threads arn't beginners concerns.

But, speaking about memory allocation without mentionning exceptions handling, memory leak risks and all the problems inherant to raw pointers (like validity, ownership ect ...) is giving an incomplete (thus wrong) answer.

C++ STL library offer more than enough tools to stay away from memory managment, better take advantage of it.
Memory managment should not be a beginner concern, they should focus on application logic.
0
Fabrice LambertFabrice LambertCommented:
Solutions provided
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.