FAQ Database Discussion Community
c++,multithreading,shared-ptr,atomic
In different threads I do the following: shared variable: std::shared_ptr<Data> dataPtr; std::atomic<int> version_number; Thread1, the producer receive new data and do dataPtr.reset(newdata); version_number++; Other threads, consumers are doing: int local_version=0; std::shared_ptr<Data> localPtr; while(local_version!=version_number) localPtr=dataPtr; ...operation on my_ptr... localPtr.reset(); local_version=version_number.load(); Here I know that the consumers might skip some version, if...
c++,vector,initialization,shared-ptr
So I am working on a transformation from an OO-language with garbage collection capabilities to C++. To start out I want to wrap all objects in shared pointers to solve the memory de-allocation issue. Right now I am trying to wrap a vector in a shared pointer and initializing the...
c++,shared-ptr,smart-pointers
So I have this code: #include <iostream> #include <list> #include <string> #include <memory> using namespace std; int main() { { shared_ptr<string> str = new string("Marius"); cout << str + " MMG"; } return 0; } By compiling it with: clang++ -Wall -g -std=c++14 test.c++ -o test I get: test.c++:11:22: error:...
c++,c++11,shared-ptr,smart-pointers
My question is that what are the various ways in which get() member from the shared_ptr class can be used? And why can't we use delete to delete it?
c++,shared-ptr,move-semantics
In the following code, I expect the memory that pointer tr points, to be destroyed. However even though I verified sp1, points to the same address with tr, and clearing the set causes the trial object sp kept to be destroyed, tr still points to the same address and the...
c++,c++11,this,shared-ptr
I have a class VectorSpace with a member createVector() which creates a Vector with a shared pointer to the referencing VectorSpace. This is achieved by std::enable_shared_from_this. However, this following code #include <memory> class Vector; class VectorSpace; class Vector { public: Vector(std::shared_ptr<VectorSpace> & space): space_(space) { }; private: std::shared_ptr<VectorSpace> space_; };...
c++,visual-studio-2013,x86,shared-ptr
I was working on a shared pointer (called Handle) implementation for my student project's game engine, and we ran into a bug that we couldn't explain. For some reason, at a certain point in our factory, there was an invalid internal pointer being passed to a factory through a handle,...
multithreading,c++11,asynchronous,design,shared-ptr
Consider an operation with a standard asynchronous interface: std::future<void> op(); Internally, op needs to perform a (variable) number of asynchronous operations to complete; the number of these operations is finite but unbounded, and depends on the results of the previous asynchronous operations. Here's a (bad) attempt: /* An object of...
c++,lambda,threadpool,shared-ptr,c++14
I'm building server for speech recognizer. I'm using thread pooling to serve clients. I needed to create unordered map to save instance of recognizer for each client. So I create this_ std::shared_ptr<std::unordered_map<int ,SOnlineSpeechRecognizerI *>> user_recognizers; std::mutex rec_mutex; So on client connection I create instance of recognizer and I need to...
c++,boost,thread-safety,shared-ptr,libc++
In boost's implementation of shared_ptr, it uses relaxed memory ordering to increment its reference count. This appears safe as decrements use acquire/release to make sure that any previous decrements are visible to the thread before releasing memory. This method seems correct and appears in Herb Sutters talk on atomics In...
c++,shared-ptr,boost-spirit,boost-spirit-qi
This is a followup question from a previous question. I can parse into vectors of strings from my grammar, but I cannot seem to parse into a vector of shared pointers to strings; i.e. std::vector<std::shared_ptr<std::string> >, and need a bit of help. My compiling header: #define BOOST_SPIRIT_USE_PHOENIX_V3 1 #include <boost/spirit/include/qi_core.hpp>...
c++,ios,boost,shared-ptr,arm64
I have a weird problem with boost shared_ptr: class A { A( ) : m_myObjectPtr( new MyObject( ) ) { } protected: boost::shared_ptr<MyObject> m_myObjectPtr; // MyObject class is a simple class with a constructor and destructor }; class B : A { B( ) { } void CleanMyObject( ) {...
c++11,move,shared-ptr,unique-ptr,unordered-set
template<class T> Class Node { //irrelavant functs }; class A { unordered_set<unique_ptr<Node<T>>, myHash<Node<T>>, myEqual<Node<T>>> nodes shared_ptr<A> child; void moveToChild() { for(auto it = nodes.begin(); it < nodes.end(); ++it) { if (some_cond) { child->nodes.emplace(std::move(*it)); } } } }; I have a class that holds bunch of nodes in unordered_set, and has...
c++,pointers,return-value,shared-ptr,return-by-reference
I am reasoning about the best approach to return references to objects created inside a method, like in the following situation: class A{ public: A(){} ~A(){} }; class Foo{ public: Foo(){} ~Foo(){} A& create(int random_arg){ // create object A and return its reference } }; void other_method(){ Foo f; A...
c++,boost,event-handling,shared-ptr,intrusive-containers
So I'm writing an event handling system using FastDelegate<> and the boost library. I need to setup a Queue of shared pointers to event data as well as a list of FastDelegate> for listeners. So here's the problem. Intrusive list and queue don't allow shared_ptr or even constant references which...
c++,c++11,destructor,shared-ptr,weak-ptr
#include <memory> #include <iostream> struct Foo { Foo() { std::cout << "Constructor ...\n"; } void doSth() {std::cout << "hi" << std::endl;} ~Foo() { std::cout << "Destructor ...\n"; } }; int main() { {std::weak_ptr<Foo> jack = (*(new std::shared_ptr<Foo>(new Foo))); std::cout << (jack).use_count() << std::endl; // std::shared_ptr<Foo> ptr = jack.lock(); // std::cout...
c++,pointers,shared-ptr,smart-pointers
I've read an "Item" about shared_ptr in Scott Meyers' book "Effective Modern C++" where he says the following: The usual control block implementation is more sophisticated than you might expect. It makes use of inheritance, and there’s even a virtual function. (It’s used to ensure that the pointed-to object is...
c++,c++11,parameters,shared-ptr
I'm using std's smartptrs recently, and I wrote mass code with "shared_ptr", there is some problems in my mind: There have two class: class base{} class drived: public base{} and also have two functions like this: void fconst(const shared_ptr<classA>& obj){} void f(shared_ptr<classA>& obj){} and this function for call test: void...
multithreading,c++11,ipc,shared-ptr
I'm trying to create an inter thread message based communications using C++11 concurrency techniques. Anthony William's book 'Concurrency in Action' describes a thread safe locking queue which this implementation is based on. The difference between the thread safe locking queue that is described in the book and the one I...
c++,pointers,shared-ptr,smart-pointers
I have created a pointer of sample class in main. I am passing this pointer to a function function1(). This function has to use pointer as shared pointer and do some operations using this pointer. During exit of function1() destructor of sample in invoked due to shared_ptr. When I pass...
c++,c++11,shared-ptr
How to make the statement shorter: auto ptr = std::shared_ptr<CPoint>(new CPoint(x, y)); Please notice the CPoint appears twice. Can it be shorter? like: auto ptr = XXXX<CPoint>(x, y); XXXX is a macro or anything. It should apply to any constructor with any parameters. auto ptrA = XXXX<ClassA>(); // a shared_ptr...
c++,shared-ptr,std-function,stdbind
I'm trying to make a forwarding call wrapper with std::bind() of an internal member function inside instance which has been created as a shared_ptr<>. Look like there's no chance. In a nutshell: std::shared_ptr<Parent> _instance(std::make_shared<Child>()); _instance->init(); _instance->proc(); // class Parent : std::enable_shared_from_this<Parent> { protected: std::vector<std::function<void()>> _vector; public: virtual void init() =...
c++,boost,shared-ptr
The following code struct Base { public: Base() { std::cout<<"Base Ctr"; } ~Base() { std::cout<<"Base Dtr"; } }; struct Derived : Base { Derived() { std::cout<<"Derived Ctr"; } ~Base() { std::cout<<"Derived Dtr"; } }; int main() { Base* b = new Derived; delete b; } gives me the following output...
c++,parsing,boost,shared-ptr,boost-spirit-qi
I would like to use a Spirit Qi grammar to parse text into shared pointers to strings. Actually, I would like to parse multivariate polynomials into a system of them, with various kinds of previously-encountered symbols appearing in the polynomials, but for now, let's parse from text into std::shared_ptr<std::string>. I...
c++,graph,memory-leaks,shared-ptr,digraphs
it's my first question here so I apologize for eventual formal mistakes you may found in my post. I'm coding a simple class for "Undirected Connected Weighted Graphs", which must use Adjacency Lists based on vectors. The issue is that when I run the program from Eclipse, MS Windows says...
c++,c++11,polymorphism,shared-ptr
I want to have a class that has a shared pointer as member: class MyClass { public: shared_ptr<MyAbstractBaseClass> myPointer; } How can I make the pointer point to an instance of a derived class?...
c++,inheritance,segmentation-fault,singleton,shared-ptr
I have a template class ISingleton class ISingleton { public: static T* getInstance() { lock_guard<mutex> guard(mMutex); if (mInstance == NULL) { mInstance = new T(); } return mInstance; } static void destroy() { lock_guard<mutex> guard(mMutex); delete mInstance; mInstance = NULL; } ISingleton(ISingleton const&) = delete; ISingleton& operator =(ISingleton const&) =...
c++,c++11,shared-ptr
This question extends Customising std::shared_ptr or boost::shared_ptr to throw an exception on NULL dereference. I want a class that behaves like shared_ptr, but that throws an exception when dereferencing a nullptr. In above's question, it was recommended to create a wrapper class that contains a shared_ptr, and to have that...
c++,qt,memory,shared-ptr
This question already has an answer here: Does calling free or delete ever release memory back to the “system” 8 answers The following places a bunch of shared_ptrs containing an arbitrary object in a QList. With the curly braces I create a stack, which triggers the deletion of the...
c++,shared-ptr,smart-pointers,c++14,perfect-forwarding
I have the following #include <iostream> #include <memory> template<typename _type> class handle { using ptr = std::shared_ptr<_type>; using pptr = std::shared_ptr<ptr>; public: handle(handle<_type> const & other) : mData(make_pptr(*(other.mData))) {} handle(_type && data) : mData(make_pptr(std::move(data))) {} private: pptr mData; template<typename ..._args> constexpr auto make_ptr(_args && ...args) { return std::make_shared<_type>(std::forward<_args>(args)...); }...
c++,dictionary,shared-ptr
Bellow I provide the complete code for something really simple which I'm struggling with.. I need to create a map with strings and Objects... When requested, if the string is inside the map, I need to return a reference to one object inside the map When the string is not...
c++,multithreading,caching,boost,shared-ptr
I have a caching system in one of my programs. I have a single, static class that maintains this cache, and use the cache in multiple threads concurrently. I am running into a problem maintaining the caching system correctly. Here is some sample code. class db_cache { public: typdef std::map<int,...
c++,c++11,shared-ptr
I have a class: class C{ public: //Omitted private: shared_ptr<X> anArray[2]; }; and X looks like: class X{ public: X(); //default constructor used by the above array declaration? private: std::unordered_map<int, double> a; }; After I create my C class, I access one of the two shared_ptr objects in the array,...
c++,c++11,shared-ptr
I have a private three dimensional vector of shared_ptr<Room> objects as follows: private: vector<vector<vector<shared_ptr<Room>>>> world; In the same class, I provide access to Room objects: public: shared_ptr<Room> room_at(const int & x, const int & y, const int & z) const { return world.at(x).at(y).at(z); } Also in the same class, I...
c++,shared-ptr,smart-pointers,unique-ptr,weak-ptr
If I understand correctly, a weak_ptr doesn't increment the reference count of the managed object, therefore it doesn't represent ownership. It simply lets you access an object, the lifetime of which is managed by someone else. So I don't really see why a weak_ptr can't be constructed from a unique_ptr,...
c++,c++11,shared-ptr
If you have a type that is quite long, in a shared_ptr, what's the easiest way to return the equivalent of a null pointer? In C++03 I was doing the following, but I'm wondering whether C++11 has introduced any better alternatives? std::shared_ptr< std::vector<std::pair<int, std::map<std::string, std::string>>> > getComplicatedType() { // Do...
c++,c++11,stl,shared-ptr
I am trying to call a const overload function void process(std::map<std::string,std::shared_ptr<const Data_Struct>>); with data I generate. Because I generate the data, I use a non-const version std::map<std::string,std::shared_ptr<Data_Struct>> my_data; When I try to call my function with process(my_data); I get the error: error C2664: 'void process(std::map<std::string,std::shared_ptr<const Data_Struct>,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>)' : cannot convert...
c++,c++11,shared-ptr,unique-ptr,weak-ptr
Maybe this question has been asked before, but I've never found a satisfactory answer. Also, for the purposes of simplicity assume I'm talking about a single-threaded application. So, what I've heard a number of times is that if you have an object that is non-owned and whose lifetime is guaranteed,...
c++11,thread-safety,shared-ptr
Suppose there is a shared_ptr: std::shared_ptr<MyClass> myPtr = std::make_shared(new MyClass()); In worker thread: myPtr = nullptr; In main thread: if( myPtr != nullptr ) { // do something } Is the code above thread safe? Or can the main thread see the new value immediately?...
c++,c++11,shared-ptr
I am reading the following piece of code as explained by the comments. #include <memory> struct myClass { ~myClass() { cout << "dtor" << endl; } }; void myFunc() { shared_ptr<myClass> sp2; { shared_ptr<myClass> sp( new myClass); myClass& obj = *sp; sp2 = sp; // OK, resource shared myClass& obj2...
c++,pointers,reference,shared-ptr,member-variables
I'd like to know what are the best practice to handle object instances as member variables of another class. After reading different posts it seems that, in general, having references to objects as member variables should be avoided, but I'm not sure if using pointers is a good solution. Another...
c++,c++11,stl,shared-ptr,weak-ptr
I am able to convert back and forth inline. std::shared_ptr<sfg::Notebook> mNotebook = ...; std::weak_ptr<sfg::Notebook> weakNotebook(mNotebook); std::shared_ptr<sfg::Notebook> strongNotebook(weakNotebook); When I attempt to pass it to a method, I get the error: "No viable conversion between std::weak_ptr<sfg::Notebook> to std::shared_ptr<sfg::Notebook>." I am calling the method normally, and the method looks like: onNotebookLeftClick(weakNotebook); void...
c++,segmentation-fault,shared-ptr,raw-pointer
If I do the following, int* p = new int(10); std::shared_ptr<int>(p); delete p; What happens here? Is the shared_ptr invalid after deletion of the raw pointer? Is there any way to ensure memory access safety in such a scenario?...
c++,inheritance,shared-ptr
I have a std::list container, holding shared pointers of say class A. I have another class, say B, that is derived from A. I currently have code that does this to populate the container: shared_ptr<B> b = shared_ptr<B>(new B); container.push_back(b) This works fine. Question is, how can I retrieve the...
c++,c++11,dictionary,shared-ptr
So on my header file I have this declaration: typedef std::map<const std::string, std::shared_ptr<House> > myHouseMap; myHouseMap _myHouseMap; On my source file I can insert an object in my map like this: _myHouseMap.insert(std::pair<const std::string, std::shared_ptr<House>>("apartment", std::make_shared<House>("apartment"))); But now, I need to return the reference of the object. Therefore, I need to...
c++,qt,overloading,shared-ptr,qhash
I just found out, to my surprise, that the following code does not compile out of the box in C++14 using Qt 5.4: QSet<std::shared_ptr<SomeType>> var; The problem is that there is no overload of the qHash() method for std::shared_ptr, or any other smart pointer as far as I can see:...
c++,shared-ptr,smart-pointers
I'm in the following scenario: struct container { data* ptr; }; void someFunc(container* receiver /* wants to be filled */) { auto myData = createData(); // returns shared_ptr<data> receiver->ptr = myData.get(); } The function that generates that data, and the object that receives it, are part of two different libraries,...
c++,pointers,c++11,shared-ptr,unique-ptr
I have a base class with a pointer member. I would have to make an educated guess to determine whether it should be an unique_ptr or a shared_ptr. None of them seems to solve my particular use case. class Base { public: Base(): pInt(std::unique_ptr<int>(new int(10))) {}; virtual std::unique_ptr<int> get() =...
c++,vector,shared-ptr,smart-pointers,shuffle
using namespace std; vector< shared_ptr<MyObject> > objects; // objects gets filled in by something random_shuffle(objects.begin(), objects.end()); Is this bad or inefficient for any reason? Is there a better way of doing it? (I want my array of smart pointers sorted randomly) EDIT: I'm asking because there are going to be...
boost,shared-ptr,pool
Should I ever prevent memory leaks using shared pointers with boost::object_pool (in case of an exception inside malloc-destroy block)? If yes, what is the correct way to initialize shared_ptr? How to clean up memory afterwards? #include <boost/pool/object_pool.hpp> #include <boost/shared_ptr.hpp> int main() { boost::object_pool<int> pool; // Which is the correct...
c++,segmentation-fault,gdb,shared-ptr
This code has run 100,000's of times before crashing around (6hrs of running in tests). When the crash happens it occurs when shared_ptr goes out of scope...the purpose of this function is to fill the passed in vector of shared_ptr ( in this case), with the messages filtered by type...So...
c++,boost,shared-ptr
I have a class like this : Header: class CurlAsio { public: boost::shared_ptr<boost::asio::io_service> io_ptr; boost::shared_ptr<curl::multi> multi_ptr; CurlAsio(); virtual ~CurlAsio(); void deleteSelf(); void someEvent(); }; Cpp: CurlAsio::CurlAsio(int i) { id = boost::lexical_cast<std::string>(i); io_ptr = boost::shared_ptr<boost::asio::io_service>(new boost::asio::io_service()); multi_ptr = boost::shared_ptr<curl::multi>(new curl::multi(*io_ptr)); } CurlAsio::~CurlAsio() { } void CurlAsio::someEvent() {...
c++,lambda,shared-ptr,pass-by-value,reference-counting
Consider the following C++ code: void f(std::function<void()> func) { func(); } void g(std::shared_ptr<MyObject> myObjPtr) { myObjPtr->someMethod(); } void h(std::shared_ptr<MyObject> myObjPtr) { f([=](){ g(myObjPtr); }); } Are there any memory leaks? My understanding is myObjPtr is copied into the lamba and has its reference count incremented. Then it's copied into g()...
c++,shared-ptr
I wanted to ask like we can do with a pointer. int q = 10; int* p = &q; How to do something with a shared_ptr? Can I use make_shared<> here? shared_ptr<int> r = make_shared<int>(q); Is this correct?...
c++,constructor,return,shared-ptr,implicit-conversion
I have a function that returns a shared_ptr to a const object. Returning a shared_ptr constructed from a pointer returned by operator new works, but returning that pointer directly causes compilation error : Error 3 error C2664: 'std::shared_ptr<_Ty>::shared_ptr(std::nullptr_t)' : cannot convert parameter 1 from 'script::float_data *' to 'std::nullptr_t' c:\xxx\value.cpp 59...
c++,boost,shared-ptr
What is so bad about doing something like this? class myclass : public std::shared_ptr<myotherclass> { // some code, an allocation is never done std::string get_info () { if(*this != nullptr) return "<info>" + (this->info * 3) + "</info>"; else return ""; } }; when no allocation is done in the...
c++,c++11,shared-ptr,c++-standard-library,make-shared
I haven't found any issues quite like this yet: but if someone finds one then sorry. I've been trying to use std::shared_ptr to greatly simplify memory management, however I've come across what must be some sort of bug. When I create a DerivedType pointer with std::make_shared<type>(DerivedType(...)) It can only be...
c++,c++11,shared-ptr
I would like to implement a base object, which can autoregister itself into a singleton object list. I would store shared pointers pointing to these objects in the list. The registration would be good to happen either in the constructor or a separate initialisation function set(). My problem is that...
c++,c++11,typedef,shared-ptr,make-shared
I have situation like this struct Foo { Foo(int x, int y) : x(x), y(y) { } int x, y; }; class Bar { public: typedef std::shared_ptr<const Foo> ConstFooPtr; typedef std::shared_ptr<Foo> FooPtr; Bar(int index = 0, FooPtr ptr = FooPtr()) : index_(index), ptr_(ptr) { } private: ConstFooPtr ptr_; int index_;...
c++,c++11,shared-ptr
I'm subclassing std::shared_ptr and am trying to write a cast() method on the subclass so I can hide static_pointer_cast, but I can't get my code to compile. What am I missing? Demo: http://ideone.com/nbPHbs template<class T> class Handle : public std::shared_ptr<T> { public: template<class ResultType> inline Handle<ResultType> cast() { // Cast...
c++,pointers,c++11,shared-ptr,smart-pointers
EDIT 3 I have the following code std::shared_ptr<int> original = std::make_shared<int>(5); std::shared_ptr<int> other = std::make_shared<int>(6); std::stack<std::shared_ptr<int>> todo; todo.push(original); std::shared_ptr<int> temp = todo.top(); *temp = *other; std::cout << original << other << temp << std::endl; original now points to the resource 6 and the output in the console is then 666....
c++,class,oop,nested,shared-ptr
I write games in C++ with SDL. I wrote games in C for more than a year and now I've been writing in C++ for the last 7 months. I'm trying to avoid almost all global variables and move to a system of ownership, where every object is owned by...
c++,c++11,design-patterns,overloading,shared-ptr
I am making a particle system and I'm struggling with how to structure my code. The idea is that a user can create one or several ParticleEmitter objects that are passed to a ParticleManager object via the ofxCurlNoise object. Now, I want that when the user updates the ParticleEmitters objects,...