smart-pointers

best practice when returning smart pointers

隐身守侯 提交于 2019-11-29 23:52:53
What is the best practice when returning a smart pointer, for example a boost::shared_ptr? Should I by standard return the smart pointer, or the underlying raw pointer? I come from C# so I tend to always return smart pointers, because it feels right. Like this (skipping const-correctness for shorter code): class X { public: boost::shared_ptr<Y> getInternal() {return m_internal;} private: boost::shared_ptr<Y> m_internal; } However I've seen some experienced coders returning the raw pointer, and putting the raw pointers in vectors. What is the right way to do it? There is no "right" way. It

How to enable_shared_from_this of both parent and derived

喜夏-厌秋 提交于 2019-11-29 23:21:46
I have simple base and derived class that I want both have shared_from_this() . This simple solution: class foo : public enable_shared_from_this<foo> { void foo_do_it() { cout<<"foo::do_it\n"; } public: virtual function<void()> get_callback() { return boost::bind(&foo::foo_do_it,shared_from_this()); } virtual ~foo() {}; }; class bar1 : public foo , public enable_shared_from_this<bar1> { using enable_shared_from_this<bar1>::shared_from_this; void bar1_do_it() { cout<<"foo::do_it\n"; } public: virtual function<void()> get_callback() { return boost::bind(&bar1::bar1_do_it,shared_from_this()); } }

C++ object-pool that provides items as smart-pointers that are returned to pool upon deletion

非 Y 不嫁゛ 提交于 2019-11-29 20:00:34
I'm having fun with c++-ideas, and got a little stuck with this problem. I would like a LIFO class that manages a pool of resources. When a resource is requested (through acquire() ), it returns the object as a unique_ptr that, upon deletion, causes the resource to be returned to the pool. The unit tests would be: // Create the pool, that holds (for simplicity, int objects) SharedPool<int> pool; TS_ASSERT(pool.empty()); // Add an object to the pool, which is now, no longer empty pool.add(std::unique_ptr<int>(new int(42))); TS_ASSERT(!pool.empty()); // Pop this object within its own scope,

What is the right smart pointer to have multiple strong references and allow mutability?

☆樱花仙子☆ 提交于 2019-11-29 17:14:23
I want to have a structure on the heap with two references; one for me and another from a closure. Note that the code is for the single-threaded case: use std::rc::Rc; #[derive(Debug)] struct Foo { val: u32, } impl Foo { fn set_val(&mut self, val: u32) { self.val = val; } } impl Drop for Foo { fn drop(&mut self) { println!("we drop {:?}", self); } } fn need_callback(mut cb: Box<FnMut(u32)>) { cb(17); } fn create() -> Rc<Foo> { let rc = Rc::new(Foo { val: 5 }); let weak_rc = Rc::downgrade(&rc); need_callback(Box::new(move |x| { if let Some(mut rc) = weak_rc.upgrade() { if let Some(foo) = Rc:

Clone pattern for std::shared_ptr in C++

£可爱£侵袭症+ 提交于 2019-11-29 16:35:23
Why do you need (in order to make it compile) the intermediate CloneImplementation and std::static_pointer_cast (see Section 3 below) to use the Clone pattern for std::shared_ptr instead of something closer (see Section 2 below) to the use of raw pointers (see Section 1 below)? Because as far as I understand, std::shared_ptr has a generalized copy constructor and a generalized assignment operator? 1. Clone pattern with raw pointers : #include <iostream> struct Base { virtual Base *Clone() const { std::cout << "Base::Clone\n"; return new Base(*this); } }; struct Derived : public Base { virtual

How to do perform a dynamic_cast with a unique_ptr?

有些话、适合烂在心里 提交于 2019-11-29 16:28:16
问题 I have a class hierarchy as follows: class BaseSession : public boost::enable_shared_from_this<BaseSession> class DerivedSessionA : public BaseSession class DerivedSessionB : public BaseSession Within the derived class functions, I regularly call functions like this: Func(boost::dynamic_pointer_cast<DerivedSessionA>(shared_from_this())); Since I was working with shared_ptr to manage the sessions, this was working fine. Recently, I discovered that my use of shared_ptr is not optimal for this

Using QSharedPointer with new[] yields “Mismatched free() / delete / delete[]” in valgrind

我是研究僧i 提交于 2019-11-29 14:49:11
I have the following code: QPair<QSharedPointer<unsigned int>, int> someclass::somefunction() { int siz = data_size(); QSharedPointer<unsigned int> buffer(new unsigned int[siz]); // Fill the buffer... return qMakePair(buffer, siz); } At some point, the QSharedPointer returned by this function will go out of scope and the pointer set in the constructor will be free'd. Using valgrind 3.6.1, I get a "Mismatched free() / delete / delete[]" error. Is there anything wrong with my use of QSharedPointer or do I just have to live with this valgrind warning? One way to fix this is to write a custom

Conditionally instantiate a template at run-time

北城余情 提交于 2019-11-29 14:45:30
I have a template class template <class T> class myClass { public: /* functions */ private: typename T::Indices myIndices; }; Now in my main code I want to instantiate the template class depending on a condition. Like : myFunc( int operation) { switch (operation) { case 0: // Instantiate myClass with <A> auto_ptr < myClass <A> > ptr = new myClass<A> (); case 1: // Instantiate myClass with <B> auto_ptr < myClass <B> > ptr = new myClass<B> (); case 2: // Instantiate myClass with <C> .... } // Use ptr here.. } Now the problem with this approach is that the auto_ptr<> will die at the end of switch

How to uniform initialize map of unique_ptr?

白昼怎懂夜的黑 提交于 2019-11-29 13:49:54
I have this code to initialize map from into to unique_ptr. auto a = unique_ptr<A>(new A()); map<int, unique_ptr<A>> m; m[1] = move(a); Can I use uniform initialize this? I tried map<int, unique_ptr<A>> m {{1, unique_ptr<A>(new A())}}; But I got an error. Some part of error message is In instantiation of 'std::_Rb_tree_node<_Val>::_Rb_tree_node(_Args&& ...) [with _Args = {const std::pair<const int, std::unique_ptr<A, std::default_delete<A> > >&}; _Val = std::pair<const int, std::unique_ptr<A> >]': ... In file included from /opt/local/include/gcc48/c++/memory:81:0, from smart_pointer_map.cpp:3:

Alternative to boost::shared_ptr in an embedded environment

a 夏天 提交于 2019-11-29 12:00:45
问题 I'm using C++ in an embedded linux environment which has GCC version 2.95 . I just can't extract boost::shared_ptr files with bcp, it is just too heavy. What I'd like would be a simple smart pointer implementation of boost::shared_ptr but without all boost overheads (if it is possible...). I could come up with my own version reading boost source but I fear missing one or more points, it seems easy to make a faulty smart pointer and I can't afford to have a buggy implementation. So, does a