Link to this pointer in the constructor

Below is another example of a forward declaration, which can be useful if the application needs a self-sustaining array of objects that can add and remove objects from themselves at runtime:

Ah file:

class A {
public:
    static A *first, *last;
    A *previous, *next;

    A();
    ~A();
};

A.cpp file:

#include "a.h"

A *A::first=0, *A::last=0; // don't put the word static here, that will cause an error

A::A() {
    if(first==0) first=this; //first A created
    previous=last;
    if(previous != 0) previous->next=this;
    last=this;
    next=0;
}

A::~A() {
    if(previous != 0) previous->next=next;
    if(next != 0) next->previous=previous;
}

From: https://en.wikipedia.org/wiki/Circular_dependency#Self-reference_example

I think the implementation Ahas a problem. While the first instance is being created A, if there are some other stream references A::first, this will lead to unexpected behavior. Please correct if I am wrong.

Also, how to solve this problem? Thanks.

+4
4

, . , A , undefined, - .

? :

  • ( , contructor destructor) . , , A. , , A .
  • , . , , .

@zvone , first last .

( ) :

A::~A() {
    if(previous != 0) previous->next=next;
    if(next != 0) next->previous=previous;
    if (first == this) first = next;
    if (last == this) last = previous;
}

:

a.h

class A {
public:
    static A *first, *last;
    A *previous, *next;
    static std::mutex mut;

    A();
    ~A();
};

a.cpp:

#include "a.h"

A *A::first=0, *A::last=0; // don't put the word static here, that will cause an error
std::mutex A::mut;

A::A() {
    mut.lock()
    if(first==0) first=this; //first A created
    previous=last;
    if(previous != 0) previous->next=this;
    last=this;
    next=0;
    mut.unlock();
}

A::~A() {
    mut.lock()
    if(previous != 0) previous->next=next;
    if(next != 0) next->previous=previous;
    if (first == this) first = next;
    if (last == this) last = previous;
    mut.unlock();
}
+2

, , , , mutextes . - - .

+1

first last , , std:: atomic

0

, . . , previous next. .

A::~A() {
    unique_lock<std::mutex> locked(A::A_mutex);
    if(previous != 0) previous->next=next;
    if(next != 0) next->previous=previous;
}

A_mutex .

0

Source: https://habr.com/ru/post/1619879/


All Articles