FAQ Database Discussion Community


C++ Pointer being freed was not allocated (possibly, an issue with unique_ptr or boost::ublas)

c++,boost,memory-leaks,unique-ptr,ublas
This is a follow up on one of my previous questions. The issue that I am dealing with is explained in detail in the formulation of this question. Unfortunately, I was not able to provide a minimal example that showcases the problem. In this question, I am making an attempt...

Is there such thing as a weak_ptr that can't be locked (promoted to shared_ptr)? If not, why?

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,...

Copying a vector of structs containing unique_ptrs

c++,smart-pointers,unique-ptr
I'm working on a simple game using C++ and Allegro. I am running into an Access violation runtime error regarding a vector of structs that contain unique_ptrs to ALLEGRO_BITMAPs. Here is my struct declaration. struct Skin { std::unique_ptr<ALLEGRO_BITMAP> img; Skin(); Skin(ALLEGRO_BITMAP*); Skin& operator=(const Skin& s); Skin(const Skin& s); }; And...

Dereferencing a temporary unique_ptr

c++,c++11,unique-ptr
unique_ptr<A> myFun() { unique_ptr<A> pa(new A()); return pa; } const A& rA = *myFun(); This code compiles but rA contains garbage. Can someone explain to me why is this code invalid? Note: if I assign the return of myFun to a named unique_ptr variable before dereferencing it, it works fine....

How to use boost::object_pool with std::unique_ptr?

c++,c++11,boost,visual-studio-2013,unique-ptr
This is a two part question illustrated by the following code: #include <memory> #include <vector> #include <boost/pool/object_pool.hpp> struct Foo { Foo(int i) : _i(i) {} void* operator new(size_t) = delete; // *** int _i; }; using FooHandle = std::unique_ptr<Foo>; struct Bar { Foo* addFoo(int i) { Foo* ptr = new...

Why doesn't this RAII move-only type properly emulate `std::unique_ptr`?

c++,c++11,move-semantics,unique-ptr
I took the code from this question and edited it to produce a segfault by explicitly calling the destructor of one of the move-constructed objects: using namespace std; struct Foo { Foo() { s = new char[100]; cout << "Constructor called!" << endl; } Foo(const Foo& f) = delete; Foo(Foo&&...

access and move unique_ptr in a function call

c++,unique-ptr
I have a segment similar to the following. struct derive : base{ derive(unique_ptr ptr): base{func(ptr->some_data), std::move(ptr)}{} }; In theory, it should work. But since the compiler (vs2015) does not strictly follow the standard, the order of func(ptr->some_data), std::move(ptr) is undefined, i.e. ptr may be moved before accessed. So my problem...

(Dangling?) Reference returned from function does not “work”

c++,pointers,reference,unique-ptr
I followed V. Romeo's Tutorial on entity management (on GitHub & Youtube). I then tried to rewrite the classes CEntity, CComponent and for testing CPosition(mostly from memory from Romeo's video/code). The problem i encounter is that, in my main i create a CEntity on the stack & add a component....

c++ Cast a vector of unique_ptr to unique_ptr where derived is a template [duplicate]

c++,c++11,vector,unique-ptr
This question already has an answer here: “Downcasting” unique_ptr<Base> to unique_ptr<Derived> 1 answer I have the following situation: Base is a base class. T is a template that can assume any derived class of Base. The underlying layer provide me data from Base class, that I need to convert...

How to assign a value of a string to a std::unique_ptr?

c++,string,unique-ptr
After declaring an std::unique_ptr<std::string> but without assigning it (so it contains an std::nullptr to begin with) - how to assign a value to it (i.e. I no longer want it to be holding std::nullptr)? Neither of the methods I've attempted work. std::unique_ptr<std::string> my_str_ptr; my_str_ptr = new std::string(another_str_var); // compiler error...

unique_ptr constructor with custom deleter is deleted

c++,visual-c++,unique-ptr
This example compiles and runs well with gcc 4.8.3: #include <memory> #include <functional> #include <iostream> int main() { auto str = new const char[6]{'h', 'e', 'l', 'l', 'o', '\0'}; std::unique_ptr<const char[], std::function<void(const char *)>> u_ptr(str, [](const char *s){ delete[] s; }); std::cout << u_ptr.get() << std::endl; } But when I...

Storing polymoprhic data types into a unique_ptr vector

c++,vector,polymorphism,function-pointers,unique-ptr
I'm having issues trying to build a program using a Unique_ptr vector to hold data from multiple classes that are derived from the same base class. I'm pretty sure the concept is correct, so I can avoid slicing my data, but I'm not sure what exactly I'm doing wrong here....

How do we return a unique_pointer member from a member function?

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() =...

If I take a raw pointer of a unique_ptr and then use reset, is the raw pointer still guaranteed to be valid?

c++,unique-ptr
Eg I'm pretty sure this works. int foo = 51; int* bar = &foo; foo = 3; So bar is still valid, and *bar == 3. What about if we say std::unique_ptr<int> foo(new int(51)); // should probably use make_unique int* bar = foo.get(); foo.reset(new int(3)); Am I guaranteed that *bar...

Why can't a weak_ptr be constructed from a unique_ptr?

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,...

Friend function is unable to construct a unique pointer of the class

c++,c++11,friend,unique-ptr
I have a certain design strategy where the constructor of my class is private and can only be constructed by friends of the class. Inside the friend function, I am trying to create a unique_pointer of my class using std::make_uniquebut it doesn't compile. My VC12 compiler complains c:\program files (x86)\microsoft...

initialize a member unique_ptr to empty

c++11,unique-ptr
In my program, I have a bunch of objects of a custom class Position. The declaration of Position is as follows: class Position { public: Position(int x, int y); ~Position(); Actor *getActor() { return actor.get(); }; void setActor(Actor *actor) { actor = std::move(actor); }; Actor *clearActor() { return actor.release(); };...

Copy semantics for C++ unique pointer

c++,c++11,unique-ptr
Is there something wrong if I write something like this: Try<std::unique_ptr<int> > some_function() { std::unique_ptr<int> s(new int(2)); return s; } Is the copy constructor invoked? Should I use std::move? ...

unique_ptr in Qt project

c++,qt,unique-ptr
I have a simple Qt project. I include <memory> but std::unique_ptr is not available. I know that I should use Qt specific smart pointers but I need to include a larger project that contains std::unique_ptr. What can I do? Thanks!...

Why doesn't `unique_ptr` degrade to `QByteArray*`?

c++,qt,c++11,unique-ptr,qbytearray
I have the following code: msg_buf_ptr = std::make_unique<QByteArray>(); return QDataStream{msg_buf_ptr, QIODevice::WriteOnly}; I am getting the following error: no known conversion for argument 1 from ‘std::unique_ptr<QByteArray>’ to ‘QByteArray*’ But...why? I thought unique_ptr and shared_ptr automatically degrade to raw pointers when passed as arguments to functions taking pointers. If not, why not?...

Can't assign iterator with no viable overloaded '=' error

c++,stl,unique-ptr
I have a field defined as const vector<record>* data; where record is defined as const unique_ptr<vector<float>> features; const float label; In my main code, I use vector<record>::iterator iter = data->begin() The compiler isn't happy with my code with the no viable overloaded '=' error at that iterator assignment line. It...

How to assign an address of an existing object to a smart pointer?

c++,smart-pointers,c++14,unique-ptr
#include <memory> class bar{}; void foo(bar &object){ std::unique_ptr<bar> pointer = &object; } I want to assign an address of the object to the pointer. The above code obviously wont compile, because the right side of the assignment operator needs to be a std::unique_ptr. I've already tried this: pointer = std::make_unique<bar>(object)...

std::unique_ptr to transfer ownership of a const object

c++,c++11,const,unique-ptr,ownership
I have an object of class A created inside a method. This method also creates an instance of an object B that takes as constructor argument the object A just created. B has to take the ownership of the object A but it can't modify it. This means that A...

C++ Pimpl Idiom Imcomplete Type using std::unique_ptr

c++,c++11,unique-ptr,pimpl-idiom,incomplete-type
I apologize for the large amount of code required to demonstrate the issue. I am having a problem using the pimpl idiom with std::unique_ptr. Specifically the problem seems to occur when one class (which has pimpl'ed implementation) is used as member data in another composite class with pimpl'ed implementation. Most...

Unable to access private member - template and std::unique_ptr

c++,templates,c++11,unique-ptr
I have the following code: #include <memory> template<typename T, size_t Level> class Foo { friend class Foo<T, Level + 1>; typedef std::unique_ptr<T> ElmPtr; typedef std::unique_ptr<Foo<ElmPtr, Level - 1>> NodePtr; public: Foo() { // no errors auto c = children; } Foo(int n) { // !!! compiler error !!! auto c...

std::unique_ptr as out argument to a function

c++11,unique-ptr
struct cls{ ~cls(){std::cout<<"dtor\n";} }; void foo(cls** pp){ *pp = new cls; } int main() { cls* raw_ptr = 0; foo(&raw_ptr); std::unique_ptr<cls> u_ptr{raw_ptr}; } Is there any way to directly access the raw_pointer in the unique_ptr to pass to the function foo(cls** pp)? Or cls* raw_ptr = 0; foo(&raw_ptr); std::unique_ptr<cls> u_ptr{raw_ptr};...

Is the contents of a pointer to a unique_ptr's contents valid after the unique_ptr is moved?

c++,pointers,move-semantics,unique-ptr
I've been led to understand that calling a member function on the contents of a moved-from std::unique_ptr is undefined behaviour. My question is: if I call .get() on a unique_ptr and then move it, will the original .get() pointer continue to point to the contents of the original unique pointer?...

std::unique_ptr and custom allocator deleter

c++,c++11,memory-management,unique-ptr,allocator
I am trying to use std::unique_ptr<T[]> with custom memory allocators. Basically, I have custom allocators that are subclasses of IAllocator, which provides the following methods: void* Alloc( size_t size ) template<typename T> T* AllocArray( size_t count ) void Free( void* mem ) template<typename T> void FreeArray( T* arr, size_t count...

How do you move a unique_ptr out of an vector>?

c++,vector,unique-ptr
I would like to move a unique_ptr<Foo> out of a vector<unique_ptr<Foo>>. Consider my code: #include <vector> #include <memory> #include <iostream> using namespace std; class Foo { public: int x; Foo(int x): x(x) {}; ~Foo() { cout << "Destroy of id: " << x << "\n"; x = -1; }; };...

Correct syntax to assign unique_ptr to new boost::asio::io_service::work object?

c++,syntax,boost-asio,unique-ptr
What's the correct syntax to assign a std::unique_ptr<boost::asio::io_service::work> pointer to a new boost::asio::io_service::work object? I am converting boost::asio code from using static functions and global variables to a class implementation, but this means I have to replace the working initialization: std::unique_ptr<boost::asio::io_service::work> KeepAlive( new boost::asio::io_service::work(TheASIOService)); with a class member variable in...

Passing unique_ptr vs raw_ptr? [duplicate]

c++,function,pointers,unique-ptr,raw-pointer
This question already has an answer here: How to pass std::unique_ptr around? 3 answers What is more common in your experience: func1() or funct2()? Assume func1 and func2 is better not as a Foo class method. void func1(unique_ptr<Bar>& bar) { /* alter pointed to object's attributes */ } void...

move semantics and unique_ptr

c++,move-semantics,unique-ptr
How would you perform a move operation on a class that uses unique_ptr? Wouldn't setting the unique_ptr to null cause deletion of the data? If I perform a copy through a list initializer of the unique_ptr like so, would the data be preserved or deleted? template<typename T, typename A =...

Concise notation for assigning `unique_ptr`?

c++11,polymorphism,unique-ptr
I have a pointer to a parent class and I want to assign a new child object to that pointer conditionally. Right now, the syntax I have is rather lengthly: std::unique_ptr<ParentClass> parentPtr; if (...) { parentPtr = std::unique_ptr<ParentClass>(new ChildClass1()); } else { parentPtr = std::unique_ptr<ParentClass>(new ChildClass2()); } Is there a...

dynamical initialization of std::vector>

c++11,vector,unique-ptr
I have a class Grid declared as follows: Grid.h #ifndef DATATEST_GRID_H #define DATATEST_GRID_H #include <memory> #include <vector> #include "Position.h" class Grid { public: Grid(int length_x, int length_y); ~Grid(); Position *at(int x, int y); void printGrid(); private: int length_x, length_y; std::vector<std::unique_ptr<Position>> grid; }; #endif Its most important member variable is the...

vector of unique_ptr not being fully deleted (memory leaks) [duplicate]

c++,visual-studio,c++11,vector,unique-ptr
This question already has an answer here: Is std::vector memory freed upon a clear? 4 answers C++ Memory Leak Using STL Containers 3 answers I'm writing a program that will eventually require me to create a vector of unique_ptrs to objects of a custom class. I was getting some...

macro for switching between auto_ptr and unique_ptr

c++,c++11,macros,unique-ptr
In a project that still uses pre-C++11 I wanted to prepare the source for the switch by compiling with a C++11 compiler and fixing the errors. They consisted of instances of std::auto_ptr<T> replaced with std::unique_ptr<T> where necessary, wrapped the smart pointer with std::move() some 0 and NULL replaced with nullptr...

c++ Passing unique_ptr as a reference to another function

c++,unique-ptr
This seens to be basic, but I need some help. I have a sample class: class myClass { int a; int b; } Then a factory: class myFactory { std::unique_ptr<myClass> getInstance() { return std::unique_ptr<myClass>(new myClass); } } Then I have several funtions that will receive myClass by reference: doSomething (myClass&...

For what is the move constructor and move assignment constructor in Unique Pointers needed?

c++,c++11,smart-pointers,move-semantics,unique-ptr
I've got a simplified example of a unique_ptr. I wonder for what the move constructor and move assignment operator in the unique pointer is needed? If I understand move constructors (and passing rvalues) right, these two lines of code should result the same. UniquePointer<T> a(new T); UniquePointer<T> a(UniquePointer<T>(new T)); And...

How to assign a unique_ptr with a custom deleter

c++,c++11,struct,unique-ptr,allegro
I am trying to pass a pointer to a function that then sets a unique_ptr inside a struct to the pointer passed in. However, I get the following compile error on the last line of the function. error C2280: 'std::unique_ptr< ALLEGRO_BITMAP,std::default_delete< ALLEGRO_BITMAP>>::unique_ptr(const std::unique_ptr< ALLEGRO_BITMAP,std::default_delete< ALLEGRO_BITMAP>> &)' : attempting to reference...

Transfering Ownership in vector of unique_ptrs

c++,vector,copy-constructor,unique-ptr,ownership
I have 2 classes A and B //A.h class A{}; // B.h typedef unique_ptr<A, AllocateA> APtr; typedef vector<APtr> BVEC; class B { public: BVEC vec; //error is here //.... }; When I compile the code I get unique_ptr....attempting to reference a deleted function I then add a copy contructor and...

Custom deleter specifications for std::unique_ptr

c++,c++11,c++14,unique-ptr
I am reading Josuttis` C++ standard library. I could not find the reasoning for the (2) and (3) comments on following example: D d; //instance of the deleter type(1) unique_ptr<int,D> p1(new int, D()); //D must be MoveConstructible(2) unique_ptr<int,D> p2(new int, d); //D must be CopyConstructible(3) What are the reasons for...

How best to make iterators for a plain array within a unique_ptr in C++11?

c++,arrays,c++11,iterator,unique-ptr
I want to use the richness of <iterator> with arrays held by unique_ptr. Here's the code I'd like to write ajuxt the code I am currently obliged to write: void question() { const int len = 10; int a[len]; unique_ptr<int[]> p(new int[len]); // i can do this with a bare...

Abusing c++11 unique_ptr to execute code upon leaving the scope

c++,c++11,unique-ptr
I want to use unique_ptr's deleter to guarantee some code will execute upon leaving the scope. For example let's say I have a class Event with function set_event(). I want to make sure that upon leaving the scope, the function my_event.set_event() will be called. I managed to get to something...

Can't use std::unique_ptr with T being a forward declaration

c++,c++11,unique-ptr,forward-declaration
Now first, I am aware of the general issues with unique_ptr<> and forward declarations as in Forward declaration with unique_ptr? . Consider these three files: A.h #include <memory> #include <vector> class B; class A { public: ~A(); private: std::unique_ptr<B> m_tilesets; }; C.cpp #include "A.h" class B { }; A::~A() {...

unique_ptr dsts(new TStringList[5]) fail

c++,c++builder,vcl,unique-ptr,tstringlist
MyEnvironment: C++ Builder XE4 I am trying to use array of TStringList using unique_ptr<>. Following was no problem: unique_ptr<int []> vals(new int [10]); On the other hand, following shows error: unique_ptr<TStringList []> sls(new TStringList [10]); The error is 'access violation at 0x000000000: read of address 0x0000000'. For TStringList, can't I...

What's wrong with this initialization of unique_ptr?

c++,c++11,initialization,unique-ptr
Can somebody tell me, what is wrong with the following initialization of unique_ptr? int main() { unique_ptr<int> py(nullptr); py = new int; .... } g++ -O2 xxx.cc -lm -o xxx -std=c++11 says: error: no match for ‘operator=’ (operand types are ‘std::unique_ptr<int>’ and ‘int*’) py = new int; ^ Doing unique_ptr<int>...

Turning this raw pointer situation into a unique_ptr?

c++,c++11,smart-pointers,unique-ptr
I have code that looks like this: ISessionUpdater* updater = nullptr; if (eventName == "test") updater = new TestJSONSessionUpdater(doc); if (eventName == "plus") updater = new PlusJSONSessionUpdater(doc); if (updater) { bool result = updater->update(data); delete updater; return result; } return false; Is there any way to do something like this...

vector of unique_ptr in C++11

c++,c++11,unique-ptr
I recently switched to C++11 and I'm trying to get used to good practices there. What I end up dealing with very often is something like: class Owner { private: vector<unique_ptr<HeavyResource>> _vectorOfHeavyResources; public: virtual const vector<const HeavyResource*>* GetVectorOfResources() const; }; This requires me to do something like adding a _returnableVector...

Removing an element from std::list of std::unique_pointer

c++,std,unique-ptr
According to this thread Returning a pointer to a vector element , it is recommended to use the following code when inserting an object into a vector and returning its pointer: // in your class std::vector<std::unique_ptr<SceneGraphNode>> m_children; SceneGraphNode* addChild(std::string name) { std::unique_ptr<SceneGraphNode> child(new SceneGraphNode(this,name)); myList.push_back(std::move(child)); return myList.back().get(); } I plan...

Add unique_ptr as instance field of a class instead of explicitly removing copy / assignment ctors

c++,c++11,copy-constructor,unique-ptr
There are some macros for preventing classes from being copied, eg: Macros to disallow class copy and assignment. Google -vs- Qt Would I get identical results just by having a unique_ptr in my class? If so, is there a reason not to do this? eg class Foo { private: std::unique_ptr<int>...

Moving a smart pointer from one unordered_set from another

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...

Is value returned by std::unique_ptr::get valid after moving unique_ptr?

c++11,move,unique-ptr
Consider the following code snippet: class Owner { public: Owner(std::unique_ptr<int> ptr) : owned_pointer<int>(std:move(ptr)) {} private: std::unique_ptr<int> owned_pointer; }; std::unique_ptr<int> ptr(new int); int* ptr1 = ptr.get(); Owner new_owner(std::move(ptr)); Is it safe to assume that ptr1 is valid as long as new_owner stays in scope? It seems to work, but I can't...

Vector of unique_ptr member

c++,c++11,unique-ptr
I have the following: typedef std::vector<std::unique_ptr<Node>> NodeList; class Node { public: Node(); Node(NodeType _type); virtual ~Node(); NodeType getNodeType() const; Node const* getParentNode() const; // I want a member function to allow acces to the // childNodes vector bool hasChildNodes() const; void setParent(Node* node); void appendChild(std::unique_ptr<Node> node); protected: NodeType _nodeType; Node*...

Error “Attempting to reference a deleted function” - when passing back value of unique_ptr

c++,c++11,unique-ptr
Test.h #include <memory> #include <string> using namespace std; class A { public: A GetTitle(); private: unique_ptr<A> title; }; Test.cpp #include <memory> #include "Test.h" A A::GetTitle() { return *this->title.get(); } // Error here int main() { } I'm getting the following error: C2280: 'std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a...

How to construct a vector with unique pointers

c++,c++11,unique-ptr,initializer-list,list-initialization
I try to construct a vector with unique_ptr. But I do not find a direct way. The following code does not compiles. The error is:Call to implicitly-deleted copy constructor of 'std::__1::unique_ptr >': #include <iostream> #include <memory> #include <utility> #include <vector> class test1{ public: test1(){}; test1(test1&&)=default; }; int main(int argc, const...

When does the unique_ptr get reset on this setter?

c++,c++11,unique-ptr
class A { ... B b; } When does the unique_ptr i passed in get removed? void A::SetB( unique_ptr<B> b ) { this->b = *b; } // At end of scope, is `b` now reset // and the `B b` in class `A` just stores the value in it? If...