Questions tagged [smart-pointers]
An abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds checking
2,788
questions
0
votes
1
answer
97
views
Threads and Shared Pointers [duplicate]
Do the new smart pointers work with threads correctly?
Ex a thread creates a copy of the pointer while another thread is in the process messing up the reference count?
0
votes
0
answers
56
views
Wiring parents/children in a direct acyclic graph in C++ with smart pointers causes SIGSEGV [duplicate]
I'm trying to build a DAG in C++20. Each node has several children as well as parents. As a MWE, each node might compute some value.
Coming from the Java world, this code works as desired:
import java....
0
votes
1
answer
63
views
Rc<[T]> try_unwrap into Vec<T>
Is there some function like try_unwrap that would allow me to obtain a slice from Rc?
Or do I have to manually check the reference count and use unsafe pointer magic to achieve this?
Edit: it looks ...
1
vote
2
answers
118
views
Equivalent of pointer in smart pointers
I am new to pointers, so consider the following code:
#include <iostream>
#include <memory>
int main()
{
double xNormal{5};
double * pNormal = &xNormal;
xNormal = 10;
...
0
votes
1
answer
130
views
Destructor called unexpectedly
Why is the destructor ~TestClass() in this simple code called twice?
#include <memory>
#include <iostream>
#include <vector>
class TestClass
{
int m_val;
public:
TestClass(int ...
0
votes
5
answers
105
views
Trying to Add Vectors with Attached Smart Pointers
I am trying to improve my coding skills by using smart pointers to handle memory management and created a simple program to add the components of two 2D vector structs and save it to a third 2D vector ...
-1
votes
4
answers
225
views
Shared Pointer query in an interview [closed]
which is better among the following codes
int *a=new int();
shared_ptr<int> sh(a);
or this
shared_ptr<int> sh(new int());
The interviewer was hinting that the first case has a problem ...
0
votes
0
answers
119
views
Can an excessive use of smart pointers lead to an increase in system kernel calls?
Can an excessive use of smart pointers (especially shared_ptr) cause an increase in kernel calls?
I am trying to optimize and simplify a real-time (QNX) codebase. One focus besides memory and realtime ...
1
vote
1
answer
42
views
Design advice: `unique_ptr` and pybind11
I have a setup in which a resource R may be passed through various filters F also deriving from R. It makes no sense to share ownership of an R because the resource is consumed upon retrieval. Some I ...
0
votes
1
answer
69
views
Rust smart pointer issue
I'm trying to implement Church numerals
//! representation of natural numbers using lambda calculus, named after
//! Alonzo Church. Each Church numeral corresponds to a natural number `n`
//! and ...
0
votes
1
answer
85
views
Why custome deleters for smart pointers are not allowed to throw exceptions?
I'm reading about smart pointers from a book and there it is specified that custom deleter is not allowed to throw. But I could not figure out the reason for this. Why they are not allowed to throw?
0
votes
1
answer
46
views
Create a smart pointer of a dynamically deduced type?
Is it possible to create a pointer of a dynamically deduced type without using an if sequence?
What should I use as a map value type?
class Vehicle {
public:
virtual void run() =0;
};
// ...
0
votes
2
answers
49
views
How to use ComPtr in C++Builder?
I'm trying to implement DX11 in my C++Builder project. All SDK references use the ComPtr<> template, eg:
// Create the DX11 API device object, and get a corresponding context.
ComPtr<...
1
vote
1
answer
63
views
How the bool operator of std::shared_ptr is trrigered in the expression(i.e. `bool is_empty = shared_ptr1 && shared_ptr2;` )?
Gaven that cur_front_res and cur_back_res are both shared_ptr, how the bool operator of std::shared_ptr is trigered in the expression(i.e. bool is_empty = cur_front_res && cur_back_res; )?
...
2
votes
2
answers
79
views
Is it safe to use std::shared_ptr between productor and consumer when the shared managed object would never be acessed at the same time?
Here is the demo code snippet below.
Could the mutex be removed since std::shared_ptr itself is thread-safe and the managed object would never be accessed by productor and consumer at the same time?
#...
0
votes
0
answers
45
views
Copying an object with a reference or pointer to another object [duplicate]
I am designing a game where I need to copy certain components.
Here is what I need:
class Common { };
class Component
{
private:
Common &_commRef;
public:
Component(Common &...
1
vote
1
answer
60
views
Why would adding a & cause a move in rust? [duplicate]
The following compiles:
#[derive(Debug)]
enum List {
Cons(Rc<RefCell<i32>>, Rc<List>),
Nil,
}
use std::ops::Deref;
use crate::List::{Cons, Nil};
use std::cell::RefCell;
use ...
0
votes
1
answer
83
views
Accessing child class variables through parent class
I am making a simple 2D physics engine for circles and squares. I have a body class that I want to be given a unique_ptr instance of a shape when created. The shape can either be a circle or a box. ...
0
votes
1
answer
89
views
What pointer type to use, when I do not know the context the pointer are used
I am developing a library, so I do not know the context of the application, that will later use the library.
I have two classes. The Window class registers Widgets, so it can eg. forward ui events to ...
-1
votes
1
answer
47
views
Smart pointers for restricted undirected graph
So I am a bit new to this whole smart pointer stuff. Now I am trying to use smart pointers for the following structure.
struct Conn {
Node* owner; //*
std::vector<Node*> targets; //Every ...
0
votes
1
answer
94
views
How do I use smart pointer to point at sibling class objects?
I am a little confused with new smart pointers. I want to use one pointer to point at two different objects of sibling classes (same parent).
so basically I have a parent class Parent and two child ...
2
votes
2
answers
101
views
Vector of Base Shared Pointers to Vector of Derived Shared Pointers
I have a class Base:
class Base
{
};
and a derived class Derived:
class Derived: public Base
{
};
Now I need to get a vector of Derived Pointers:
std::vector<std::shared_ptr<Derived>> ...
-1
votes
1
answer
54
views
My own Smart pointer Implementation is creating issue with move operation
In the below code, the output is turning out to be blank instead of constructor and destructor printouts. Without move operation, the code is working well. I am somehow messing up the move operation, ...
1
vote
1
answer
81
views
What is the correct way to use smart pointers with CMFCPropertyGridProperty?
What is the correct way for using smart pointers with property grid controls so that I don't have to use new?
For example:
auto AddSection = [](CMFCPropertyGridCtrl *pGrid, CString strSection) -> ...
-2
votes
1
answer
76
views
Iterating over a vector of shared_ptrs in a range-based for loop
I feel like this should have an answer already but I wasn't able to find it.
I have a vector of shared_ptrs:
vector<shared_ptr<X>> v;
I don't want to do anything with ownership (e.g. ...
0
votes
1
answer
53
views
Does the temporary of a smart pointer have a reference count, or if so, does it insrement its reference count?
I have a question while reading "Section 12.1" of "C++ Primer 5th". It can be described as followed:
auto p = std::shared_ptr<int>(new int(42));
std::cout << p....
2
votes
1
answer
134
views
Is there a C++ smart pointer that represents a terminal pointer?
I'm playing around with smart pointers in C++, using shared_ptr and unique_ptr and weak_ptr. Let's say I have a shared_ptr that I share among multiple owners, but I have a set of consumers that want ...
2
votes
2
answers
75
views
Different scenerios of custom deleter for unique_ptr
was reading Nicholai Jossutis, STL book. There is a part like
D d; // instance of the deleter type
unique_ptr<int, const D&> p4(new int, D()); // ...
3
votes
1
answer
129
views
How should I initialise a shared-pointer member?
I can initialize a std::shared_ptr member in 2 different ways in my constructor (which both increment its use_count):
Pass by reference:
class MyClass {
std::shared_ptr<std::string> s1;
...
0
votes
0
answers
129
views
Safely share unique_ptr across threads
How do you safely share unique_ptr across threads? I need one thread to be able to reset the underlying object, and the other thread to be able to access it in a safe way.
There is no atomic_exchange ...
0
votes
1
answer
50
views
Swapping private unique pointers with a public method
I have a class with a private unique_ptr member and I want to expose a public swap function which will swap ownership of its unique_ptr member with that of the provided other. How can I do so?
class A{...
0
votes
1
answer
101
views
How to use smart pointer to manage existing object
Suppose I have a vector of data generated from some API. It's for plotting only.
vector<double> LineData = generateData();
I also have a class that do the plotting and manage the data
class ...
1
vote
3
answers
77
views
Initialise std::shared_ptr using value initialisation
I was experimenting with braced initialisation and specifically using value initialisation.
To my understanding int x {} uses value initialisation to set the value of x to 0.
So I then tried this with ...
2
votes
1
answer
77
views
Convert std::unique_ptr of derived to base and pass ownership as argument
I have this code:
#include <iostream>
#include <memory>
class Base
{
public:
virtual void doSmth() = 0;
};
class Der1 : Base
{
public:
void doSmth() final
{
std::cout ...
1
vote
0
answers
30
views
How should declare SWIG interface if some types can be wrapped with either shared_ptr or just value type?
In SWIG, I tried to use shared_ptr as below.
class Member {
};
class Parent {
private:
std::shared_ptr<Member> member_;
};
class OtherParent {
private:
Member member_;
}
%...
6
votes
1
answer
103
views
Memory leak using unique pointer and polymorphism
I know that std::unique_ptr doesn't guarantee memory safety and especially it is true in the case of circular dependency. However, in my case, I can't see it. Child contain Parent(or SecondChild in ...
-2
votes
1
answer
69
views
Dynamic memory allocation of smart pointers declared in a class in C++ [closed]
I see such kind of code regularly in C++
struct StructExample{
StructExample(int a, int b):mA(a), mB(b){
}
int mA;
int mB;
}
class ExampleClass{
public:
void foo();
private:
...
0
votes
0
answers
13
views
multithread std::shared_ptr read / write with sigsegv
a global shared_ptr g_ptr=null;
then in thread 1, call init() set g_ptr=make_shared();
after that, has other thread x use write()
void write()
{
if(g_ptr)
{
g_ptr->dosomething();// ...
2
votes
1
answer
89
views
How do smart pointer performance concerns compare in server core codebases (e.g Google's) vs large scale time critical embedded systems (e.g NASA)?
In his cpp con 2019 talk, Chandler Carruth argues that c++ std::unique_ptr is not a truly zero cost (runtime) abstraction: https://www.youtube.com/watch?v=rHIkrotSwcc&t=6s.
I work on an embedded ...
0
votes
0
answers
65
views
Cannot instantiate the abstract class
Here are my projects files compiled with VS:
Init.h
#pragma once
#include <iostream>
#include <memory>
#include "Ishare.h"
using namespace std;
class Init {
private:
std::...
1
vote
1
answer
124
views
Why does the copy constructor is not called?
#include <iostream>
#include <memory>
using namespace std;
class Init {
private:
int x;
public:
Init(int y) {
x = y;
cout << "default constructor ...
0
votes
0
answers
62
views
QT New Ui and Shared Pointer
I am trying to build a UI which reads a json file and displays the information in QT UI.There are mainly three classes involved Travelagency(a class which reads the json file), Holiday(Main UI) and ...
2
votes
1
answer
74
views
Is it required to reset the shared_ptr object initialized in a function(local variable)? and global to the file?
Initialized global static shared_ptr object and passed to a function:
#include <iostream>
#include <memory>
std::shared_ptr<int> globalObj = std::make_shared<int>(5);
int ...
0
votes
0
answers
71
views
How to find out if C++ memory was allocated with scalar new or array new
I am working on optimizing my smart pointer in my C++ library. The pointer has, besides from the built-in pointer and reference count, a boolean stating whether the pointer is scalar or array (i.e. it ...
4
votes
1
answer
263
views
std::unique_ptr with custom deleter for wrapping a malloc pointer
I have a C library function:
uint8_t* c_func();
This either returns a valid uint8_t pointer allocated with malloc(), or NULL on error. I want to wrap it in a std::unique_ptr() as follows:
struct ...
0
votes
2
answers
99
views
Can I create a pointer in my header file, pointing to a function in another cpp file?
I have a func in my abc.cpp file
namespace myNamespace{
void Gif::myfunc(){
//code
}
}
In anotherHeader.h file:
void createPointer(){
void(*funcPtr)()=&Gif::myfunc;
}
can I do this, or ...
0
votes
0
answers
35
views
why Box<Option<T>> can directly use Option API [duplicate]
I am trying to implement a Trie data structure in rust, here's the code with my questions in comments
#[derive(Default)]
pub struct Trie {
is_word: bool,
children: [Box<Option<Trie>&...
-3
votes
2
answers
152
views
What should be the C# equivalent of Rust's Box<> type? [closed]
I am translating Rust code into C#.
Rust has some type called Box<> which is said to be C++'s equivalent of smart pointers.
What should be the C# equivalent of Rust's Box<> type?
0
votes
0
answers
26
views
The correct way to handle smart pointers in Dependency Injection in C++ [duplicate]
I'm implementing the Dependency Injection pattern in C++ with smart pointers. When using std::unique_ptr I'm wondering if there is any difference passing pointers in the constructor by rvalue ...
1
vote
1
answer
166
views
std::make_unique and designated initializers
Consider this structure:
struct MyStruct
{
int my_number;
std::string my_string;
};
Is it possible to create a std::unique_ptr using Designated initializers? Like this:
// like this
auto ...