This document contains lecture slides about memory management in C++. It discusses static variables, constructors and destructors, and use of new and delete operators. Static variables are shared among all class instances and changes to them affect all instances. Constructors initialize objects and destructors clean them up. new allocates memory on the heap while delete frees it and calls the destructor.
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...Igalia
By Daniel Ehrenberg.
Slides at https://docs.google.com/presentation/d/1bpvESaWtNnhXV0a95b6GWHhhqUVnGCIPcs37ngqx4Uo/edit#slide=id.g38b91fc952_0_103
Following ES6, TC39 is working with the broader JS developer community to continue evolving the JavaScript programming language. The pipeline operator `x |> f |> g` is an early stage, community-driven proposal to make it easier to compose multiple functions, inspired by similar syntax in other programming language and frameworks like RxJS. In this talk, I'll explain how TC39 works and how this proposal is being carefully developed with extensive feedback and opportunities for you to get involved.
(c) WorkerConf 2018
28th June 2018 (Dornbirn, Austria)
https://worker.sh/
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...Igalia
By Daniel Ehrenberg.
Slides at https://docs.google.com/presentation/d/1bpvESaWtNnhXV0a95b6GWHhhqUVnGCIPcs37ngqx4Uo/edit#slide=id.g38b91fc952_0_103
Following ES6, TC39 is working with the broader JS developer community to continue evolving the JavaScript programming language. The pipeline operator `x |> f |> g` is an early stage, community-driven proposal to make it easier to compose multiple functions, inspired by similar syntax in other programming language and frameworks like RxJS. In this talk, I'll explain how TC39 works and how this proposal is being carefully developed with extensive feedback and opportunities for you to get involved.
(c) WorkerConf 2018
28th June 2018 (Dornbirn, Austria)
https://worker.sh/
A small introduction on the C++14 improved static introspection of the IOD library and the C++14 web framework Silicon.
https://github.com/matt-42/silicon
https://github.com/matt-42/iod
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)AvitoTech
В своём докладе Влад будет говорить об использовании STL, управлении памятью, как работает ARC и C++, лямбды и блоки. И самое главное: где и как можно «выстрелить себе в ногу».
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
SubScript - это расширение языка Scala, добавляющее поддержку конструкций и синтаксиса аглебры общающихся процессов (Algebra of Communicating Processes, ACP). SubScript является перспективным расширением, применимым как для разработки высоконагруженных параллельных систем, так и для простых персональных приложений.
Rainer Grimm, “Functional Programming in C++11”Platonov Sergey
C++ это мультипарадигменный язык, поэтому программист сам может выбирать и совмещать структурный, объектно-ориентированный, обобщенный и функциональный подходы. Функциональный аспект C++ особенно расширился стандартом C++11: лямбда-функции, variadic templates, std::function, std::bind. (язык доклада: английский).
In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).
A small introduction on the C++14 improved static introspection of the IOD library and the C++14 web framework Silicon.
https://github.com/matt-42/silicon
https://github.com/matt-42/iod
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)AvitoTech
В своём докладе Влад будет говорить об использовании STL, управлении памятью, как работает ARC и C++, лямбды и блоки. И самое главное: где и как можно «выстрелить себе в ногу».
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
SubScript - это расширение языка Scala, добавляющее поддержку конструкций и синтаксиса аглебры общающихся процессов (Algebra of Communicating Processes, ACP). SubScript является перспективным расширением, применимым как для разработки высоконагруженных параллельных систем, так и для простых персональных приложений.
Rainer Grimm, “Functional Programming in C++11”Platonov Sergey
C++ это мультипарадигменный язык, поэтому программист сам может выбирать и совмещать структурный, объектно-ориентированный, обобщенный и функциональный подходы. Функциональный аспект C++ особенно расширился стандартом C++11: лямбда-функции, variadic templates, std::function, std::bind. (язык доклада: английский).
In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxDeepasCSE
Certainly, here's a brief explanation of constructors, destructors, and operator overloading without using code:
Constructors: Constructors are special methods used to initialize objects of a class. They set the initial state of an object when it is created.
Destructors: Destructors are special methods used to clean up resources and perform necessary cleanup when an object is no longer needed or goes out of scope. They ensure proper resource management.
Operator Overloading: Operator overloading is a feature that allows you to define custom behaviors for operators such as +, -, *, /, etc., when they are applied to objects of your class. It enables you to work with objects in a way that is meaningful for your specific class.
Constructors can be of different types:
Default Constructors: Initialize objects with default values.
Parameterized Constructors: Accept arguments to initialize objects with specific values.
Copy Constructors: Create a new object as a copy of an existing object.
Constructor Overloading: A class can have multiple constructors with different parameter lists, providing flexibility in object initialization.
Destructors are executed automatically when an object is destroyed. They are essential for releasing resources like memory, file handles, or network connections, ensuring proper cleanup and preventing resource leaks.
Operator overloading enables you to define how operators work with objects of your class. For instance, you can specify what the + operator does when applied to two objects of your class, allowing for custom operations that make sense in the context of your class's functionality.
In summary, constructors initialize objects, destructors handle cleanup, and operator overloading allows custom operations with operators when working with objects. These features are crucial for building custom classes in object-oriented programming.
C# - what's new with C# 7, what's planned with C# 8: productivity, performance, avoiding errors with tuples, pattern matching, nullable reference types, and more
C# ist eine Programmiersprache mehrerer Paradigmen. C# war nie rein objektorientiert, schon in der ersten Version als Component-basierte Sprache angepriesen. Mit der Zeit gab es Erweiterungen der deklarativen Programmierung, und auch funktionale Konzepte wurden bei C# übernommen. In welche Richtung entwickelt sich C# weiter? In dieser Session werden neueste Erweiterungen von C# gezeigt. Themen sind dabei die letzten aktuellen Änderungen sowie geplante Erweiterungen wie z. B. die Vermeidung von NullReferenceException mit Non-Nullable Reference Types und die Reduktion von Garbage-Collector-Aufrufen mit Hilfe von Memory-Optimierungen.
Sencha Roadshow 2017: Modernizing the Ext JS Class System and ToolingSencha
JavaScript is advancing and ES2015 (formerly ES6) is the foundation of its future. Sencha is committed to delivering cutting-edge technology for your applications, and supporting the evolution of JavaScript is a central part of that commitment. The expansive feature set of ES2015 formally enables coding paradigms: modules to better organize your code, classes to cleanly declare reusable units of functionality, and so much more. In this session, you'll see how Ext JS is embracing these new language and toolset features, and how they will expand your development horizons.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
Data privacy is one of the most critical issues that businesses face. This presentation shares insights on the principles and best practices for ensuring the resilience and security of your workload.
Drawing on a real-life project from the HR industry, the various challenges will be demonstrated: data protection, self-healing, business continuity, security, and transparency of data processing. This systematized approach allowed to create a secure AWS cloud infrastructure that not only met strict compliance rules but also exceeded the client's expectations.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
Strategies for Successful Data Migration Tools.pptxvarshanayak241
Data migration is a complex but essential task for organizations aiming to modernize their IT infrastructure and leverage new technologies. By understanding common challenges and implementing these strategies, businesses can achieve a successful migration with minimal disruption. Data Migration Tool like Ask On Data play a pivotal role in this journey, offering features that streamline the process, ensure data integrity, and maintain security. With the right approach and tools, organizations can turn the challenge of data migration into an opportunity for growth and innovation.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
Prosigns: Transforming Business with Tailored Technology Solutions
201801 CSE240 Lecture 13
1. CSE240 – Introduction to
Programming Languages
Lecture 13:
Programming with C++ | memory management
Javier Gonzalez-Sanchez
javiergs@asu.edu
javiergs.engineering.asu.edu
Office Hours: By appointment
2. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 2
Outline
• static,
• constructor and destructor,
• new and delete
4. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 4
Example
1. #include <iostream>
2. using namespace std;
3. class Foo {
4. public:
5. void counting();
6. int getCounterB();
7. static int counterA;
8. private:
9. int counterB;
10. };
11.
12. // initial value to static member variable
13. int Foo::counterA = 0;
14. int counter = 0;
A static variable is shared by all the
objects from a class. Therefore,
changes made to a static variable will
impact all objects from the class
5. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 5
1. #include <iostream>
2. using namespace std;
3. class Foo {
4. public:
5. void counting();
6. int getCounterB();
7. static int counterA;
8. private:
9. int counterB;
10. };
11.
12. // initial value to static member variable
13. int Foo::counterA = 0;
14. int counter = 0;
Example
static versus global Variables
static variables prevents functions
outside the class to access the
variable. As a global variable, all
other functions can read/write it.
A static variable is shared by all the
objects from a class. Therefore,
changes made to a static variable will
impact all objects from the class
6. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 6
Example
18. void Foo::counting() { // Set a new mil Time
19. counterA++;
20. counterB++;
21. }
22. int Foo::getCounterB() {
23. return counterB;
24. }
25. int main() {
26. Foo f1, f2, f3;
27. f1.counting();
28. f2.counting();
29. f2.counting();
30. f3.counting();
31. cout << Foo::counterA<<endl;
32. cout << f1.getCounterB()<<endl;
33. cout << Foo::counterA<<endl;
34. cout << f2.getCounterB()<<endl;
35. return 0;
36. }
A static variable go out of scope only
if the program terminated. And it can
be used even without creating an
object from the class.
8. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 8
Constructor and Destructor
A constructor in a class:
• is a function whose name is same as the class name, and
• is used to automatically initialize objects.
A destructor in a class:
• is a function whose name is same as the class name (with a ~ as
prefix), and
• is used to collect garbage.
9. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 9
Constructor and Destructor
#include <iostream>
using namespace std;
class Queue {
private:
int queue_size;
protected:
int *buffer;
int front;
int rear;
public:
Queue();
Queue(int n);
~Queue();
};
Queue::Queue() { // constructor
cout << "constructor(void)"<<endl;
// code...
}
Queue::Queue(int n) { // constructor overload
cout << "constructor (int)"<<endl;
// code...
}
Queue::~Queue(void) {
cout << "destructor"<<endl;
// code...
}
int main () {
Queue myQueue1(500);
Queue myQueue2;
// more code...
return 0;
}
10. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 10
Constructor and Destructor
#include <iostream>
using namespace std;
class Queue {
private:
int queue_size;
protected:
int *buffer;
int front;
int rear;
public:
Queue();
Queue(int n);
~Queue();
};
Queue::Queue() { // constructor
cout << "constructor(void)"<<endl;
// code...
}
Queue::Queue(int n) { // constructor overload
cout << "constructor (int)"<<endl;
// code...
}
Queue::~Queue(void) {
cout << "destructor"<<endl;
// code...
}
int main () {
Queue myQueue1(500);
Queue myQueue2;
// more code...
return 0;
}
11. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 11
When is a destructor called?
• When a local object (from stack) with block scope goes out of scope.
• When a program (main function) ends and global or static objects
exist (OS will collect them anyway).
• When the destructor is explicitly called.
• When the delete keyword is called.
13. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 13
new and delete
int main () {
Queue myQueue2(500);
// declare a pointer only
Queue *myQueue;
// reserve memory for an object
myQueue = new Queue(500);
// use the object
myQueue->enqueue(23);
myQueue2.enqueue(8);
// delete will call ~Queue();
delete myQueue;
...
delete myQueue2;//no needed
}
14. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 14
new and delete with constructors and destructors
#include <iostream>
using namespace std;
class Queue {
private:
int queue_size;
protected:
int *buffer;
int front;
int rear;
public:
Queue();
Queue(int n);
~Queue();
};
Queue::Queue() { // constructor
cout << "constructor(void)"<<endl;
// code...
buffer = NULL;
}
Queue::Queue(int n) { // constructor overload
cout << "constructor (int)"<<endl;
// code...
buffer = new int[queue_size];
}
Queue::~Queue(void) {
cout << "destructor"<<endl;
// code...
delete [] buffer;
}
int main () {
Queue myQueue1(500);
Queue myQueue2;
Queue *myQueue3 = new Queue(100);
// more code...
delete myQueue3;
return 0;
}
15. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 15
Summary
• If an object is on the stack, instead of on the heap, destructor will be
called when the object goes out of scope. No delete operation is
necessary.
• All heap objects must be explicitly deleted before leaving the
function, if they are no longer needed.
• The function delete will implicitly call the destructor of the class, so
that an object linked to a variable in the to-be-deleted object can
be de-allocated too, i.e., using delete for variables created in the
class (normally in the constructor).
16. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 16
delete and Array of Objects
#include <iostream>
using namespace std;
#define size 4
class arrayObject {
public:
int x; double y;
arrayObject() { cout << "arrayObject's constructor called" << endl; }
~arrayObject() { cout << "arrayObject's destructor called" << endl; }
};
int main() {
arrayObject *p, *q; // declare two pointers
p = new arrayObject[size]; // Create an array of objects
for (q = p; q < p + size; q++) { // Initialize the objects
q->x = 10; q->y = 1.5;
}
for (q = p; q < p + size; q++) {
cout << "Element address " << q << " Element x value: " << q->x << endl;
cout << "Element address " << q << " Element y value: " << q->y << endl;
}
delete[] p;
return 0;
}
17. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 17
Summary
• How do we delete an array of objects?
We can use a loop to delete each element,
• However, the language provides a library function to delete all
the elements one by one without the user to explicitly use a loop:
delete[] array;
18. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 18
Summary
Java
• Primitive variables (int, float, boolean) use value type.
• All other variables (string, array, user defined classes) use reference type. (Java uses
automatic garbage collection).
C++
• Both value and reference types exist:
• if value semantics used then memory is allocated on stack or on static by compiler.
Memory de-allocation is done automatically.
• if reference semantics used (e.g. variable is a pointer to an object), then memory must
be allocated explicitly using new and explicitly de-allocated using delete
19. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 19
Summary
// in C++
Report r; // an object is allocated to r
Report *rp1, *rp2; // two pointers declared
rp1 = &r; // rp1 points to object r
rp2 = new Report(); // an object is created, linked to rp2
// ..
delete rp2;
// in Java
Report r; // an reference is allocated
r = new Report (); // an object is created and linked to r
20. CSE240 – Introduction to Programming Languages
Javier Gonzalez-Sanchez
javiergs@asu.edu
Fall 2017
Disclaimer. These slides can only be used as study material for the class CSE240 at ASU. They cannot be distributed or used for another purpose.