logo
down
shadow

How can I track object lifetime in C++11 lambda?


How can I track object lifetime in C++11 lambda?

Content Index :

How can I track object lifetime in C++11 lambda?
Tag : cpp , By : Vasiliy
Date : November 23 2020, 01:01 AM

I wish did fix the issue. Extend object lifetime
Lambdas can capture shared pointers to this, so an object won't die while at least one lambda exists.
class Foo : public std::enable_shared_from_this<Foo> {
public:
    Foo(const std::string& i_name) : name(i_name) {}

    std::function<void()> GetPrinter() {
        std::shared_ptr<Foo> that = shared_from_this();

        return [that]() {
            std::cout << that->name << std::endl;
        };
    }

    std::string name;
};
class Foo : public std::enable_shared_from_this<Foo> {
public:
    Foo(const std::string& i_name) : name(i_name) {}

    std::function<void()> GetPrinter() {
        std::weak_ptr<Foo> weak_this = shared_from_this();

        return [weak_this]() {
            auto that = weak_this.lock();
            if (!that) {
                std::cout << "The object is already dead" << std::endl;
                return;
            }

            std::cout << that->name << std::endl;
        };
    }

    std::string name;
};
struct lifetime_tracker
{
private:
    struct shared_state
    {
        std::uint32_t count : 31;
        std::uint32_t dead  : 1;
    };

public:
    struct monitor
    {
        monitor() : state(nullptr) {}

        monitor(shared_state *i_state) : state(i_state) {
            if (state)
                ++state->count;
        }

        monitor(const monitor& t) : state(t.state) {
            if (state)
                ++state->count;
        }

        monitor& operator=(monitor t) {
            std::swap(state, t.state);
            return *this;
        }

        ~monitor() {
            if (state) {
                --state->count;
                if (state->count == 0 && state->dead)
                    delete state;
            }
        }

        bool alive() const {
            return state && !state->dead;
        }

    private:
        shared_state *state;
    };

public:
    lifetime_tracker() : state(new shared_state()) {}
    lifetime_tracker(const lifetime_tracker&) : state(new shared_state()) {}
    lifetime_tracker& operator=(const lifetime_tracker& t) { return *this; }

    ~lifetime_tracker() {
        if (state->count == 0)
            delete state;
        else
            state->dead = 1;
    }

    monitor get_monitor() const {
        return monitor(state);
    }

private:
    shared_state *state;
};
class Foo {
public:
    Foo(const std::string& i_name) : name(i_name) {}

    std::function<void()> GetPrinter() {
        auto monitor = tracker.get_monitor();

        return [this, monitor]() {
            if (!monitor.alive()) {
                std::cout << "The object is already dead" << std::endl;
                return;
            }

            std::cout << this->name << std::endl;
        };
    }

private:
    lifetime_tracker tracker;

    std::string name;
};

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Why lifetime of temporary doesn't extend till lifetime of enclosing object?


Tag : cpp , By : John Phipps
Date : March 29 2020, 07:55 AM
Does that help The standard considers two circumstances under which the lifetime of a temporary is extended:
B* f() {
   B * bp = new B(A());
   return b;
}
void test() {
   B* p = f();
   delete p;
}

Track QStandardItem lifetime


Tag : qt , By : Bo.
Date : March 29 2020, 07:55 AM
I wish this help you As is often the case in Qt, there are objects that are not QObjects, but that are managed by a QObject (or otherwise accessible via one). You need to make MyObject monitor the model the items are in. The code below could be a starting point.
Another approach, not implemented but certainly feasible, is to dynamically replace all items in a model with copies that are instances that you yourself created. By monitoring the relevant model signals, you can be notified of all item additions and replace items with instances that you are a factory for. It would be a thinly veiled dependency injection into a QStandardItemModel.
class MyObject : public QObject {
  Q_OBJECT
  QStandardItem * m_item;
  Q_SLOT void onRowsAboutToBeRemoved(const QModelIndex & parent, int start, int end) {
    if (m_item->parent() == parent &&
        m_item->index().row() >= start &&
        m_item->index().row() <= end) onItemGone;
  }
  Q_SLOT void onColumnsAboutToBeRemoved(const QModelIndex & parent, int start, int end) {
    if (m_item->parent() == parent &&
        m_item->index().column() >= start &&
        m_item->index().column() <= end) onItemGone;
  }
  Q_SLOT void onItemGone() {
    m_item = 0;
    deleteLater();
  }
public:
  MyObject(QStandardItem* item, QObject * parent = 0) :
    QObject(parent), m_item(item)
  {
    Q_ASSERT(m_item.model());
    connect(m_item.model(), SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
            SLOT(onRowsAboutToBeRemoved(QModelIndex,int,int)));
    connect(m_item.model(), SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
            SLOT(onColumnsAboutToBeRemoved(QModelIndex,int,int)));
    connect(m_item.model(), SIGNAL(modelAboutToBeReset()), SLOT(onItemGone());
    connect(m_item.model(), SIGNAL(destroyed()), SLOT(onItemGone());
  }
};

Cannot infer an appropriate lifetime for lifetime parameter cloning trait object


Tag : rust , By : Pradeep Gowda
Date : March 29 2020, 07:55 AM
seems to work fine The error message is quite confusing in this case, but notice a double ampersand here: (expected &&std::collections::HashMap>, found &&std::collections::HashMap>).
It looks like it tries to clone the reference. I assume you wanted to clone the entire HashMap. Calling clone explicitly as Clone::clone(spiders) gives much clearer error message:
error[E0277]: the trait bound `Spider: std::clone::Clone` is not satisfied
error[E0277]: the trait bound `Spider: std::marker::Sized` is not satisfied
  --> error_orig.rs:19:26
   |
19 |     let thread_spiders = Clone::clone(spiders);
   |                          ^^^^^^^^^^^^ the trait `std::marker::Sized` is not implemented for `Spider`
   |
   = note: `Spider` does not have a constant size known at compile-time
   = note: required because of the requirements on the impl of `std::clone::Clone` for `Box<Spider>`
   = note: required because of the requirements on the impl of `std::clone::Clone` for `std::collections::HashMap<std::string::String, Box<Spider>>`
   = note: required by `std::clone::Clone::clone`
pub trait Spider: Sync + Send {
    fn add_request_headers(&self, headers: &mut Vec<String>);
    fn clone_into_box(&self) -> Box<Spider>;
}

impl Clone for Box<Spider> {
    fn clone(&self) -> Self {
        self.clone_into_box()
    }
}

#[derive(Clone)]
pub struct Google {}

impl Spider for Google {
    fn add_request_headers(&self, headers: &mut Vec<String>) {
        headers.push("Hello".to_string())
    }

    fn clone_into_box(&self) -> Box<Spider> {
        Box::new(self.clone())
    }
}

Using Mutex to track another app's lifetime


Tag : chash , By : Michael Gunderson
Date : March 29 2020, 07:55 AM
wish helps you This pseudocode enables MyApp1 to wait for MyApp2 to launch and then detect when user exits MyApp2:
HANDLE hMutex = nullptr;
while (hMutex == nullptr && !timedout)
{
    hMutex = OpenMutex(
        SYNCHRONIZE,
        FALSE,
        "MyApp2IsRunning");
    Sleep(1000);
}
if (timedout){return error;}
DWORD wait_result = WaitForSingleObject(hMutex, INFINITE);

Lifetime of object in lambda connected to pyqtSignal


Tag : python , By : JulianCT
Date : March 29 2020, 07:55 AM
With these it helps The lambda in your example forms a closure. That is, it is a nested function that references objects available in its enclosing scope. Every function that creates a closure keeps a cell object for every item it needs to maintain a reference to.
In your example, the lambda creates a closure with references to the local self and model variables inside the scope of the __init__ method. If you keep a reference to the lambda somewhere, you can examine all the cell objects of its closure via its __closure__ attribute. In your example, it would display something like this:
>>> print(func.__closure__)
(<cell at 0x7f99c16c5138: MyModel object at 0x7f99bbbf0948>, <cell at 0x7f99c16c5168: MyClass object at 0x7f99bbb81390>)
TypeError: 'managedbuffer' object is not callable
Related Posts Related QUESTIONS :
  • simple c++ file opening issue
  • Switching from C++ (with a lot of STL use) to C for interpreter building
  • How can I access the JPEG image pixels as a 3D array like we do in MATLAB?
  • What wording in the C++ standard allows static_cast<non-void-type*>(malloc(N)); to work?
  • Avoid allocating in constructor or preserve simplicity (and RAII?)
  • Can C++ raise an error when std array initialization is too small?
  • Reference to end is ambiguous
  • Problem with basic usage of std::enable_if
  • How to print out a decimal number as octal number using setiosflags in C++
  • Open Visual Studio with solution and specific file and line
  • Enum value based on template type
  • Is there any way to swap nodes in std::list?
  • How to copy QString into wchar_t buffer
  • Make the compiler generate an empty default function for an std::function
  • Insert or push_back to end of a std::vector?
  • Best practice for const temporary types
  • Include CSV File in Complied Binary
  • Issue with binding non static function to callback
  • How can read from some files and write content of them with different form into files with same names
  • Why does auto deduce this variable as double and not float?
  • no instance of overloaded function "std::make_unique" matches the argument list, but works with unique_ptr con
  • How to see array size from a pointer in c++
  • Error taking address of temporary in Eclipse
  • Using an iterator to go through a vector and modify the contents
  • Are extern extern "C", and extern "C" extern, allowed?
  • Can't solve C2660 and C2065 Errors
  • C referencing C++ extern
  • How to write the definition of a derived class in c++?
  • Why when I include <cmath> I need to use the namespace std too?
  • How to assign a 32-bit unsigned integer to a bit field containing 32 bits
  • Why does the same class being defined in multiple .cpp files not cause a linker multiple definition error?
  • C++ 11db error when trying to quit the program in xcode. beginner level
  • Add content of a vector into a Capnproto map object
  • Recursively Pass Template Template To a Template Template Function
  • Swap rows in a 2D array with std::swap. How does it work?
  • Is there any situation in which an object's storage might change during its lifetime?
  • clang++ always generates empty profraw coverage reports
  • Do memory leaks persist after program completion if the OS does not clear it?
  • How to link library using cmake
  • How to use getters and setters without generating a copy?
  • Generating multiple amounts of the same sprite broken
  • function in c++ why my compiler didn't recognize the error()
  • Relationship between copy(...) and copy(seq, ...)
  • Are <cmath> functions required to be `noexcept` in C++17?
  • How to find a struct list item
  • How can you handle DLL versions when referencing C++ DLL's over COM from VBScript with CreateObject?
  • Do not understand how c++ set works
  • Actual build date in C++
  • How to link to already compiled external shared libraries in RCPP using Makevars?
  • combination of enable_if + std::less + sizeof... makes MSVC fail
  • Can you call the destructor without calling the constructor?
  • How do I prevent a function from freeing memory of a local variable?
  • Why am I getting an exception with a push involved with a shared pointer?
  • Resizing an array by pointer
  • avoiding dynamic_cast without increasing coupling
  • I cannot solve the else part in my if-else ladder?
  • Inherit from arbitrary class in c++?
  • LNK2019 unresolved external symbol from MSVCRTD.lib
  • Do I need to free wchar memory allocated when using 'new' or does delete[] also free it?
  • Object creation with varying buffer size
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com