SlideShare une entreprise Scribd logo
1  sur  13
Télécharger pour lire hors ligne
Qt Smart Pointers

    By Roman Okolovich
Overview
       Memory management in C++ is left up to the
        programmer.
       Smart pointers are the preferred way in C++ to
        ensure correct management of dynamic memory
        allocated by new expressions.
       Smart pointers are similar to regular pointers, but
        take care of the details of deleting the object being
        pointed to when it is no longer needed.
       The C++ Standard Library already contains
        std::auto_ptr, a smart pointer with transfer-of-
        ownership semantics.
       New C++ Standard may be issued by the end of
        2010 and it will introduce new smart pointers.

    2                                           7 February 2010
General
       Shared pointer versus shared data
           When you share pointers, the value of the pointer and its
            lifetime is protected by the smart pointer class but the object
            that the pointer is pointing to is completely outside its control.
           Sharing of data involves the smart pointer class knowing
            something about the data being shared (Implicitly Shared Qt
            Classes).
       Strong versus weak pointer
           Strong pointers own the object they point to. Multiple strong
            pointers can share ownership. An object is guaranteed to stay
            alive as long as at least one strong pointer still points to it.
           Weak pointers observe an object. They can be used exactly
            like strong pointers, but they do not keep their object alive. If an
            object is destructed, all of its weak pointers will be valued null.

    3                                                        7 February 2010
C++0x smart pointers
       std::shared_ptr<>
           The shared_ptr is a reference-counted pointer that acts as
            much as possible like a regular C++ data pointer. The shared
            pointer will automatically destroy its contents only when there
            are no shared pointers referencing the object originally created
            for the shared pointer.
       std::weak_ptr<>
           A weak_ptr is a reference to an object referenced by a
            shared_ptr that can determine if that object has been deleted or
            not. weak_ptr itself cannot be dereferenced; accessing the
            actual pointer requires the creation of a shared_ptr object.
       std::unique_ptr<>
           unique_ptr will be provided as a replacement for auto_ptr which
            will be deprecated. It provides all the features of auto_ptr with
            the exception of unsafe implicit moving from lvalues. Unlike
            auto_ptr, unique_ptr can be used with the C++0x move-aware
            containers.
       Currently GCC since 4.3 and MSVC 2010 support C++0x
    4                                                     7 February 2010
Qt smart pointers
       QPointer (4.0)
       QSharedDataPointer (4.0)
       QExplicitlySharedDataPointer (4.4)
       QSharedPointer (4.5)
       QWeakPointer (4.5)
       QScopedPointer (4.6)

       Internal
           QtPatternist::AutoPtr (internal class, 4.4)
           QGuard (internal class, 4.6)


    5                                                     7 February 2010
QPointer
       QPointer is a weak pointer class and it shares the pointer
        value, not the data.
       It only operates on QObject and QObject-derived classes.
           QPointer has one serious flaw: it lets you know whether the object
            has been deleted, but it makes no guarantee about the next line!
            For example, the following code could be in trouble:
            QPointer<QObject> o = getObject();
             // […]
             if (!o.isNull())
                 o->setProperty(“objectName”, “Object”);
           Even if isNull() returns false, there’s no guarantee that the object
            won’t get deleted by the next line.
       Therefore, QPointer can only be used to access the object if
        you can guarantee, by external means, that the object won’t
        get deleted. For example, QWidget and its descendents can
        only be created, manipulated and deleted in the GUI thread. If
        your code is running on the GUI thread or has that thread
        blocked, then QPointer usage is safe.


    6                                                         7 February 2010
QSharedDataPointer
       The most important of the smart pointer classes in Qt.
       It provides implicit sharing, with thread-safe copy-on-write.
       The QSharedData class is used as a base class for shared data objects.
       QSharedDataPointer requires that the class have a member called ref (see QAtomicInt member in
        QSharedData class)
            The member offers a function called ref() for increasing the reference count and another called
             deref() that decreases that reference count and returns false when it drops to zero.
       QSharedDataPointer members:
            inline void detach() {if (d && d->ref != 1) detach_helper();}
            inline T * operator->() {detach(); return d; }
            inline const T *operator->() const { return d; }
            private:
              T *d;
            Any non-const access will cause the data to be copied.
       The size of a QSharedDataPointer object is exactly the size of a pointer
            That means it’s possible to replace normal pointers with it in the code without breaking Binary
             Compatibility.
       This class is the basis of all Qt value-type, implicit-shared, thread-safe copy-on-write recent
        classes.
            The only reason why it isn’t used in the base classes like QByteArray, QString and QList is that those
             classes were developed before this class was made.
       So QSharedDataPointer is a strong smart pointer class, sharing data.



    7                                                                                   7 February 2010
QExplicitlySharedDataPointer
       The QExplicitlySharedDataPointer class represents a pointer
        to an explicitly shared object.
       This class is exactly like QSharedDataPointer (so it’s a strong
        smart pointer class, sharing data), with the only difference that
        it do not do the automatic copy on write operation (detach())
        that non-const members of QSharedDataPointer do before
        allowing the shared data object to be modified.
       There is a detach() function available, but if you really want
        to detach(), you have to call it yourself. This means that
        QExplicitlySharedDataPointers behave like regular C++
        pointers, except that by doing reference counting and not
        deleting the shared data object until the reference count is 0,
        they avoid the dangling pointer problem.
       QExplicitlySharedDataPointer members:
        inline void detach() {if (d && d->ref != 1) detach_helper();}
        inline T *operator->() { return d; }
        inline const T *operator->() const { return d; }
    8                                                  7 February 2010
QSharedDataPointer versus
QExplicitlySharedDataPointer
class EmployeeData : public QSharedData // can be defined in a separate file
{
 public:
  EmployeeData() : id(-1) { name.clear(); }
  EmployeeData(const EmployeeData &other)
                : QSharedData(other), id(other.id), name(other.name) { }
  ~EmployeeData() {}
  int id; QString name;
};
//------ the public file ------------------------------------------------------
class EmployeeData; // predeclare the private subclass
class Employee
{
 public:
  Employee() { d = new EmployeeData; }
  Employee(int id, QString name) {d = new EmployeeData(); setId(id); setName(name);}
  Employee(const Employee &other) : d (other.d) {}
 void setId(int id) { d->id = id; }
 void setName(QString name) { d->name = name; }
 int id() const { return d->id; }
 QString name() const { return d->name; }
 private: // a copy constructor or an assignment operator are not needed
  QSharedDataPointer<EmployeeData> d;
};
int main(int argc, char *argv[])
{
  Employee e1(1001, "Albrecht Durer");
  Employee e2 = e1;
  int i = e2.id();
  e1.setName("Hans Holbein"); // a copy on write is performed for QSharedDataPointer
}
 9                                                              7 February 2010
QSharedPointer
    The QSharedPointer class holds a strong reference to a shared
     pointer.
    The QSharedPointer is an automatic, shared pointer in C++. It
     behaves exactly like a normal pointer for normal purposes, including
     respect for constness.
        it is polymorphic, it supports static, const, and dynamic casts, it implements
         atomic reference-counting and thread-safe semantics (it’s only for the
         pointer itself: remember it shares the pointer, not the data), it supports
         custom deleters.
    QSharedPointer will delete the pointer it is holding when it goes out of
     scope, provided no other QSharedPointer objects are referencing it.
    A QSharedPointer object can be created from a normal pointer,
     another QSharedPointer object or by promoting
     a QWeakPointer object to a strong reference.
    It comes with a cost, though: to support polymorphism correctly, the
     size of QSharedPointer is actually twice the size of a normal pointer.
     This means you cannot maintain binary compatibility while replacing a
     normal pointer with it in public parts of your API. You can use it
     internally in your code, though.

    10                                                          7 February 2010
QWeakPointer
    The QWeakPointer class holds a weak reference to a shared
     pointer.
    The QWeakPointer is an automatic weak reference to a
     pointer in C++. It cannot be used to dereference the pointer
     directly, but it can be used to verify if the pointer has been
     deleted or not in another context.
    QWeakPointer objects can only be created by assignment
     from a QSharedPointer and they let you know when a
     QSharedPointer has been deleted.
          QWeakPointer<Data> weak(getSharedPointer());
          QSharedPointer<Data> ptr = weak.toStrongRef();
          if ( !ptr.isNull() )
           ptr->doSomething();
        In this case, the promotion of a QWeakPointer to a
         QSharedPointer will either succeed or it won’t. But that’s a thread-
         safe decision.
    QWeakPointer can be used to track deletion classes derives
     from QObject. It is more efficient than QPointer, so it should be
     preferred in all new code.
    11                                                    7 February 2010
QScopedPointer
    The QScopedPointer class stores a pointer to a dynamically allocated object, and
     deletes it upon destruction.
    It provides a very nice way to do RAII (Resource Acquisition Is Initialization).
    It implements a non-shared strong pointer wrapper.
    QScopedPointer guarantees that the object pointed to will get deleted when the
     current scope disappears.
    It intentionally has no copy constructor or assignment operator, such that ownership
     and lifetime is clearly communicated.
void myFunction(bool useSubClass)
{ // assuming that MyClass has a virtual destructor
  QScopedPointer<MyClass> p(useSubClass ? new MyClass() : new MySubClass);
  QScopedPointer<QIODevice> device(handsOverOwnership());
  if (m_value > 3) return;
  process(device);
}
    QSharedPointer has the size of two pointers.
    It also has a custom deleter as a template parameter, as opposed to a parameter to
     the constructor (like QSharedPointer does): it has no space in those 4 or 8 bytes to
     store the custom deleter.
    QScopedPointer and QExplicitlySharedDataPointer are already used all over the
     place in the Qt for S60.

    12                                                              7 February 2010
References
    Pointer (computing)
    Smart pointer
    C++0x
    Introducing QScopedPointer
    Count with me: how many smart pointer classes
     does Qt have?




    13                                   7 February 2010

Contenu connexe

Tendances

Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++Mohammad Shaker
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Abu Saleh
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingFrancesco Casalegno
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Sameer Rathoud
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Gamindu Udayanga
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++Ilio Catallo
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 FeaturesJan Rüegg
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - CJussi Pohjolainen
 
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrineFrankie Dintino
 

Tendances (20)

Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect Forwarding
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Linked list
Linked listLinked list
Linked list
 
C++11
C++11C++11
C++11
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
C++ references
C++ referencesC++ references
C++ references
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
Modern C++
Modern C++Modern C++
Modern C++
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
OpenGL 4.6 Reference Guide
OpenGL 4.6 Reference GuideOpenGL 4.6 Reference Guide
OpenGL 4.6 Reference Guide
 
C++11
C++11C++11
C++11
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
 
OpenGL ES 3 Reference Card
OpenGL ES 3 Reference CardOpenGL ES 3 Reference Card
OpenGL ES 3 Reference Card
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
 
OpenGL ES 3.1 Reference Card
OpenGL ES 3.1 Reference CardOpenGL ES 3.1 Reference Card
OpenGL ES 3.1 Reference Card
 

En vedette

C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointerschchwy Chang
 
Effective stl notes
Effective stl notesEffective stl notes
Effective stl notesUttam Gandhi
 
Статический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий ЛевановСтатический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий ЛевановYandex
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)Ovidiu Farauanu
 
Effective c++notes
Effective c++notesEffective c++notes
Effective c++notesUttam Gandhi
 
Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)Daniele Pallastrelli
 
C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersRichard Thomson
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and deletePlatonov Sergey
 
Михаил Матросов, “С++ без new и delete”
Михаил Матросов, “С++ без new и delete”Михаил Матросов, “С++ без new и delete”
Михаил Матросов, “С++ без new и delete”Platonov Sergey
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingDustin Chase
 
C++ Dependency Management 2.0
C++ Dependency Management 2.0C++ Dependency Management 2.0
C++ Dependency Management 2.0Patrick Charrier
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101Tim Penhey
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKamal Acharya
 
Introduction to Bitcoin and ECDSA
Introduction to Bitcoin and ECDSAIntroduction to Bitcoin and ECDSA
Introduction to Bitcoin and ECDSANikesh Mistry
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done rightPlatonov Sergey
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)Olve Maudal
 
difference between c c++ c#
difference between c c++ c#difference between c c++ c#
difference between c c++ c#Sireesh K
 

En vedette (20)

C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointers
 
Effective stl notes
Effective stl notesEffective stl notes
Effective stl notes
 
Статический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий ЛевановСтатический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий Леванов
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
 
Effective c++notes
Effective c++notesEffective c++notes
Effective c++notes
 
Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)
 
C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmers
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and delete
 
Михаил Матросов, “С++ без new и delete”
Михаил Матросов, “С++ без new и delete”Михаил Матросов, “С++ без new и delete”
Михаил Матросов, “С++ без new и delete”
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
STL Algorithms In Action
STL Algorithms In ActionSTL Algorithms In Action
STL Algorithms In Action
 
C++ Dependency Management 2.0
C++ Dependency Management 2.0C++ Dependency Management 2.0
C++ Dependency Management 2.0
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
 
File Pointers
File PointersFile Pointers
File Pointers
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Introduction to Bitcoin and ECDSA
Introduction to Bitcoin and ECDSAIntroduction to Bitcoin and ECDSA
Introduction to Bitcoin and ECDSA
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
Differences between c and c++
Differences between c and c++Differences between c and c++
Differences between c and c++
 
difference between c c++ c#
difference between c c++ c#difference between c c++ c#
difference between c c++ c#
 

Similaire à Smart Pointers

C questions
C questionsC questions
C questionsparm112
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndEdward Chen
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
C++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming languageC++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming languageHariTharshiniBscIT1
 
ObjectLayout: Closing the (last?) inherent C vs. Java speed gap
ObjectLayout: Closing the (last?) inherent C vs. Java speed gapObjectLayout: Closing the (last?) inherent C vs. Java speed gap
ObjectLayout: Closing the (last?) inherent C vs. Java speed gapAzul Systems Inc.
 
C++ tutorial boost – 2013
C++ tutorial   boost – 2013C++ tutorial   boost – 2013
C++ tutorial boost – 2013Ratsietsi Mokete
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)PROIDEA
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basicsmhtspvtltd
 
Conflict-Free Replicated Data Types (PyCon 2022)
Conflict-Free Replicated Data Types (PyCon 2022)Conflict-Free Replicated Data Types (PyCon 2022)
Conflict-Free Replicated Data Types (PyCon 2022)Rebecca Bilbro
 
Introduction to C++ Programming
Introduction to C++ ProgrammingIntroduction to C++ Programming
Introduction to C++ ProgrammingPreeti Kashyap
 

Similaire à Smart Pointers (20)

C questions
C questionsC questions
C questions
 
Java unit i
Java unit iJava unit i
Java unit i
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
C++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming languageC++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming language
 
ObjectLayout: Closing the (last?) inherent C vs. Java speed gap
ObjectLayout: Closing the (last?) inherent C vs. Java speed gapObjectLayout: Closing the (last?) inherent C vs. Java speed gap
ObjectLayout: Closing the (last?) inherent C vs. Java speed gap
 
Treinamento Qt básico - aula II
Treinamento Qt básico - aula IITreinamento Qt básico - aula II
Treinamento Qt básico - aula II
 
C++ tutorial boost – 2013
C++ tutorial   boost – 2013C++ tutorial   boost – 2013
C++ tutorial boost – 2013
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
 
Bound and Checked
Bound and CheckedBound and Checked
Bound and Checked
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
 
01 objective-c session 1
01  objective-c session 101  objective-c session 1
01 objective-c session 1
 
Conflict-Free Replicated Data Types (PyCon 2022)
Conflict-Free Replicated Data Types (PyCon 2022)Conflict-Free Replicated Data Types (PyCon 2022)
Conflict-Free Replicated Data Types (PyCon 2022)
 
Introduction to C++ Programming
Introduction to C++ ProgrammingIntroduction to C++ Programming
Introduction to C++ Programming
 
SRAVANByCPP
SRAVANByCPPSRAVANByCPP
SRAVANByCPP
 

Plus de Roman Okolovich

Plus de Roman Okolovich (11)

Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
C# XML documentation
C# XML documentationC# XML documentation
C# XML documentation
 
code analysis for c++
code analysis for c++code analysis for c++
code analysis for c++
 
Using QString effectively
Using QString effectivelyUsing QString effectively
Using QString effectively
 
Ram Disk
Ram DiskRam Disk
Ram Disk
 
64 bits for developers
64 bits for developers64 bits for developers
64 bits for developers
 
Virtual Functions
Virtual FunctionsVirtual Functions
Virtual Functions
 
Visual Studio 2008 Overview
Visual Studio 2008 OverviewVisual Studio 2008 Overview
Visual Studio 2008 Overview
 
State Machine Framework
State Machine FrameworkState Machine Framework
State Machine Framework
 
The Big Three
The Big ThreeThe Big Three
The Big Three
 
Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
 

Dernier

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 

Dernier (20)

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 

Smart Pointers

  • 1. Qt Smart Pointers By Roman Okolovich
  • 2. Overview  Memory management in C++ is left up to the programmer.  Smart pointers are the preferred way in C++ to ensure correct management of dynamic memory allocated by new expressions.  Smart pointers are similar to regular pointers, but take care of the details of deleting the object being pointed to when it is no longer needed.  The C++ Standard Library already contains std::auto_ptr, a smart pointer with transfer-of- ownership semantics.  New C++ Standard may be issued by the end of 2010 and it will introduce new smart pointers. 2 7 February 2010
  • 3. General  Shared pointer versus shared data  When you share pointers, the value of the pointer and its lifetime is protected by the smart pointer class but the object that the pointer is pointing to is completely outside its control.  Sharing of data involves the smart pointer class knowing something about the data being shared (Implicitly Shared Qt Classes).  Strong versus weak pointer  Strong pointers own the object they point to. Multiple strong pointers can share ownership. An object is guaranteed to stay alive as long as at least one strong pointer still points to it.  Weak pointers observe an object. They can be used exactly like strong pointers, but they do not keep their object alive. If an object is destructed, all of its weak pointers will be valued null. 3 7 February 2010
  • 4. C++0x smart pointers  std::shared_ptr<>  The shared_ptr is a reference-counted pointer that acts as much as possible like a regular C++ data pointer. The shared pointer will automatically destroy its contents only when there are no shared pointers referencing the object originally created for the shared pointer.  std::weak_ptr<>  A weak_ptr is a reference to an object referenced by a shared_ptr that can determine if that object has been deleted or not. weak_ptr itself cannot be dereferenced; accessing the actual pointer requires the creation of a shared_ptr object.  std::unique_ptr<>  unique_ptr will be provided as a replacement for auto_ptr which will be deprecated. It provides all the features of auto_ptr with the exception of unsafe implicit moving from lvalues. Unlike auto_ptr, unique_ptr can be used with the C++0x move-aware containers.  Currently GCC since 4.3 and MSVC 2010 support C++0x 4 7 February 2010
  • 5. Qt smart pointers  QPointer (4.0)  QSharedDataPointer (4.0)  QExplicitlySharedDataPointer (4.4)  QSharedPointer (4.5)  QWeakPointer (4.5)  QScopedPointer (4.6)  Internal  QtPatternist::AutoPtr (internal class, 4.4)  QGuard (internal class, 4.6) 5 7 February 2010
  • 6. QPointer  QPointer is a weak pointer class and it shares the pointer value, not the data.  It only operates on QObject and QObject-derived classes.  QPointer has one serious flaw: it lets you know whether the object has been deleted, but it makes no guarantee about the next line! For example, the following code could be in trouble: QPointer<QObject> o = getObject(); // […] if (!o.isNull()) o->setProperty(“objectName”, “Object”);  Even if isNull() returns false, there’s no guarantee that the object won’t get deleted by the next line.  Therefore, QPointer can only be used to access the object if you can guarantee, by external means, that the object won’t get deleted. For example, QWidget and its descendents can only be created, manipulated and deleted in the GUI thread. If your code is running on the GUI thread or has that thread blocked, then QPointer usage is safe. 6 7 February 2010
  • 7. QSharedDataPointer  The most important of the smart pointer classes in Qt.  It provides implicit sharing, with thread-safe copy-on-write.  The QSharedData class is used as a base class for shared data objects.  QSharedDataPointer requires that the class have a member called ref (see QAtomicInt member in QSharedData class)  The member offers a function called ref() for increasing the reference count and another called deref() that decreases that reference count and returns false when it drops to zero.  QSharedDataPointer members: inline void detach() {if (d && d->ref != 1) detach_helper();} inline T * operator->() {detach(); return d; } inline const T *operator->() const { return d; } private: T *d;  Any non-const access will cause the data to be copied.  The size of a QSharedDataPointer object is exactly the size of a pointer  That means it’s possible to replace normal pointers with it in the code without breaking Binary Compatibility.  This class is the basis of all Qt value-type, implicit-shared, thread-safe copy-on-write recent classes.  The only reason why it isn’t used in the base classes like QByteArray, QString and QList is that those classes were developed before this class was made.  So QSharedDataPointer is a strong smart pointer class, sharing data. 7 7 February 2010
  • 8. QExplicitlySharedDataPointer  The QExplicitlySharedDataPointer class represents a pointer to an explicitly shared object.  This class is exactly like QSharedDataPointer (so it’s a strong smart pointer class, sharing data), with the only difference that it do not do the automatic copy on write operation (detach()) that non-const members of QSharedDataPointer do before allowing the shared data object to be modified.  There is a detach() function available, but if you really want to detach(), you have to call it yourself. This means that QExplicitlySharedDataPointers behave like regular C++ pointers, except that by doing reference counting and not deleting the shared data object until the reference count is 0, they avoid the dangling pointer problem.  QExplicitlySharedDataPointer members: inline void detach() {if (d && d->ref != 1) detach_helper();} inline T *operator->() { return d; } inline const T *operator->() const { return d; } 8 7 February 2010
  • 9. QSharedDataPointer versus QExplicitlySharedDataPointer class EmployeeData : public QSharedData // can be defined in a separate file { public: EmployeeData() : id(-1) { name.clear(); } EmployeeData(const EmployeeData &other) : QSharedData(other), id(other.id), name(other.name) { } ~EmployeeData() {} int id; QString name; }; //------ the public file ------------------------------------------------------ class EmployeeData; // predeclare the private subclass class Employee { public: Employee() { d = new EmployeeData; } Employee(int id, QString name) {d = new EmployeeData(); setId(id); setName(name);} Employee(const Employee &other) : d (other.d) {} void setId(int id) { d->id = id; } void setName(QString name) { d->name = name; } int id() const { return d->id; } QString name() const { return d->name; } private: // a copy constructor or an assignment operator are not needed QSharedDataPointer<EmployeeData> d; }; int main(int argc, char *argv[]) { Employee e1(1001, "Albrecht Durer"); Employee e2 = e1; int i = e2.id(); e1.setName("Hans Holbein"); // a copy on write is performed for QSharedDataPointer } 9 7 February 2010
  • 10. QSharedPointer  The QSharedPointer class holds a strong reference to a shared pointer.  The QSharedPointer is an automatic, shared pointer in C++. It behaves exactly like a normal pointer for normal purposes, including respect for constness.  it is polymorphic, it supports static, const, and dynamic casts, it implements atomic reference-counting and thread-safe semantics (it’s only for the pointer itself: remember it shares the pointer, not the data), it supports custom deleters.  QSharedPointer will delete the pointer it is holding when it goes out of scope, provided no other QSharedPointer objects are referencing it.  A QSharedPointer object can be created from a normal pointer, another QSharedPointer object or by promoting a QWeakPointer object to a strong reference.  It comes with a cost, though: to support polymorphism correctly, the size of QSharedPointer is actually twice the size of a normal pointer. This means you cannot maintain binary compatibility while replacing a normal pointer with it in public parts of your API. You can use it internally in your code, though. 10 7 February 2010
  • 11. QWeakPointer  The QWeakPointer class holds a weak reference to a shared pointer.  The QWeakPointer is an automatic weak reference to a pointer in C++. It cannot be used to dereference the pointer directly, but it can be used to verify if the pointer has been deleted or not in another context.  QWeakPointer objects can only be created by assignment from a QSharedPointer and they let you know when a QSharedPointer has been deleted. QWeakPointer<Data> weak(getSharedPointer()); QSharedPointer<Data> ptr = weak.toStrongRef(); if ( !ptr.isNull() ) ptr->doSomething();  In this case, the promotion of a QWeakPointer to a QSharedPointer will either succeed or it won’t. But that’s a thread- safe decision.  QWeakPointer can be used to track deletion classes derives from QObject. It is more efficient than QPointer, so it should be preferred in all new code. 11 7 February 2010
  • 12. QScopedPointer  The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon destruction.  It provides a very nice way to do RAII (Resource Acquisition Is Initialization).  It implements a non-shared strong pointer wrapper.  QScopedPointer guarantees that the object pointed to will get deleted when the current scope disappears.  It intentionally has no copy constructor or assignment operator, such that ownership and lifetime is clearly communicated. void myFunction(bool useSubClass) { // assuming that MyClass has a virtual destructor QScopedPointer<MyClass> p(useSubClass ? new MyClass() : new MySubClass); QScopedPointer<QIODevice> device(handsOverOwnership()); if (m_value > 3) return; process(device); }  QSharedPointer has the size of two pointers.  It also has a custom deleter as a template parameter, as opposed to a parameter to the constructor (like QSharedPointer does): it has no space in those 4 or 8 bytes to store the custom deleter.  QScopedPointer and QExplicitlySharedDataPointer are already used all over the place in the Qt for S60. 12 7 February 2010
  • 13. References  Pointer (computing)  Smart pointer  C++0x  Introducing QScopedPointer  Count with me: how many smart pointer classes does Qt have? 13 7 February 2010