Questions tagged [raii]

Resource Acquisition Is Initialization (RAII) is a common idiom used in C++ to manage the lifetime of resources, including memory allocations, file handles or database connections. In brief, every resource should be wrapped in an owning class, whose lifetime controls the lifetime of the resource.

Filter by
Sorted by
Tagged with
0 votes
2 answers
94 views

How to achieve RAII with #pragma's?

Currently, I have the following piece of code: enum class Letters { A, B, C }; #pragma GCC diagnostic push #pragma GCC diagnostic error "-Wswitch" Letters e(Letters::A);...
neutrion's user avatar
3 votes
1 answer
77 views

Why adding a defaulted move assignment operator breaks compilation of standard swap function?

In the following code, if move assignment is uncommented the swap function stops compilation of the program. I observed this behavior on all 3 major compilers (GCC, Clang, MSVC). #include <utility&...
Xeverous's user avatar
  • 1,005
-1 votes
1 answer
102 views

Vulkan-hpp m_dispatcher->getVkHeaderVersion() != VK_HEADER_VERSION

i'm trying to use vulkan raii and create an Instance (and in fact instantiation a vk::raii::Context) i got this error /usr/include/vulkan/vulkan_raii.hpp:2660: const vk::raii::ContextDispatcher* vk::...
Amir Khaki's user avatar
1 vote
1 answer
46 views

RAII style guard with Rust gives invalid lifetime errors

I am writing a lexer and want to advance/backup a cursor using RAII helpers. I have a string that is indexed by the CharStreamGuard type that acts as the cursor. It is created at the top-level with ...
user1055947's user avatar
3 votes
0 answers
95 views

Why does the std::scope_success destructor check if uncaught exceptions are less or equal

According to https://en.cppreference.com/w/cpp/experimental/scope_success/~scope_success The destructor of std::scope_success checks if the current number of uncaught exception (std::...
tmlen's user avatar
  • 8,563
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{...
ajsdiubfaoishd's user avatar
1 vote
1 answer
152 views

RAII using custom deleter of unique_ptr

I want to do automatic cleanup using std::unique_ptr but to initialize the unique_ptr I need an address to point to. How can I avoid the noUse variable? bool noUse; auto deleter = [](bool *){ ...
Mohit's user avatar
  • 1,949
1 vote
2 answers
19 views

scope objects in boost::spirit and RAII

In some languages a new scope can be opened and closed again. In C++ this would be the curly brace. Assuming one creates a new scope on encountering an opening curly brace and closes it on ...
Frank Puck's user avatar
0 votes
1 answer
82 views

Why use defer lock with unique lock

Why use defer lock? What is with taking ownership first then locking? Isn't taking ownership and locking kinda same. What if we took ownership using unique lock of a mutex and not locking, could it ...
SameemSh.'s user avatar
1 vote
1 answer
52 views

C++ Error Handling without bypassing stack unwinding process

I want to have clean error handling in my code that consists of many source and header files. What I would prefer is using traditional C-style status codes (call function which returns 1 on success, ...
stackoverfIow's user avatar
1 vote
0 answers
33 views

Rust borrow checker complains about multiple reference even after out of scope [duplicate]

I'm trying to write a simple variable environment stack for an interpreter. The design is essentially a linked list of hashmap, where each hashmap represents a nested scope, starting from global. My ...
techhara's user avatar
0 votes
0 answers
53 views

Is it bad class design to have deferred initialization of complex class?

I know RAII and was trying to stick to single step instantiation. As long as all arguments for members are given, instance is valid, and it destruct at destructor. However, if the class is big enough ...
YoonSeok OH's user avatar
2 votes
3 answers
144 views

Using std::optional to invalidate my RAII object in move constructor/asignment [closed]

Say I have an RAII class, instances of which should never be copied: class Session { public: Session(); // Allocates a resource and sets generates a unique Session::id. ~Session(); // Frees ...
John O'brien's user avatar
1 vote
0 answers
76 views

Class design: How to implement RAII ressource management for Log-Listener class

EDIT: Alright, the question does not seem to be suitable for the platform as there is no real technical background here. No problem (really, no sarcasm), I will look somewhere else for advice. Thanks ...
Markus Moll's user avatar
1 vote
0 answers
24 views

RAII Monitor in C# with Monitor

Been looking for a "wrapper" class for Monitor.TryEnter, so that my code doesn't look horrendous. Does anything like this already exist? I would rather not roll my own. I was thinking ...
bpeikes's user avatar
  • 3,527
2 votes
1 answer
63 views

RAII when using ascyc c library

I have an RAII wrapper around the cnats library. We don't need to understand the details of cnats. There are just two important piecies. cnats is the C client for communicating with a NATS message ...
John Sallay's user avatar
0 votes
0 answers
132 views

Why partial move a struct in Rust will drop its unmoved field when the move and constructor occurs in same line? [duplicate]

struct Foo { a: String, b: Bar, } impl Default for Foo{ fn default() -> Self { Foo { a: "a".to_string(), b: Bar} } } struct Bar; impl Drop for Bar { fn drop(...
stef zhang's user avatar
3 votes
0 answers
354 views

Getting rid of dynamic allocation in C++20 coroutines

According to this open-std discussion the compiler is allowed to optimize out dynamic allocation of coroutines that are created and destroyed within a stack activation frame which makes sense to me. ...
glades's user avatar
  • 3,935
0 votes
1 answer
332 views

Does a user-defined drop for a struct also drop its fields implicitly in Rust?

Let's say I have a struct struct Foo { a: Box<usize>, b: Box<usize>, } And I'd like to do something with a and b when dropping a Foo instance like this impl Drop for Foo { fn ...
zoey1771's user avatar
0 votes
0 answers
54 views

Resource management Kotlin/Android in unstructured code without RAII

I made a post over at the Kotlin subreddit about some reliability problems I've been having in an Android project I'm working on at work. From some of the really great comments and discussions there, ...
kyp4's user avatar
  • 133
2 votes
3 answers
220 views

Rust solution for RAII pattern to modify another object on new() and drop()

It's pretty standard in C++ to have an arrangement like: // Some object that you want to manipulate class DataType { public: foo() {} bar() {} }; // Some class that manipulates a ...
Michael Balloni's user avatar
0 votes
1 answer
115 views

How to manage memory for captured inputs of a lambda? [duplicate]

So in modern C++ we use smart pointers to make sure that a shared resource didn't get deleted before we go to use it. Is there an equivalent for std::function<> for lambda callbacks? Where you ...
Natio2's user avatar
  • 235
0 votes
0 answers
134 views

`C` RAII wrapper without encapsulation?

I'm trying to make few small RAII wrappers around C library, and struggling with all the consequences of OOP style solutions, like too keep solution consistent I need to cover all methods of the C ...
Artsiom Miksiuk's user avatar
0 votes
1 answer
118 views

std::unique_ptr custom deleters seem to need a pointer argument -- is there an alternative that can take a non-pointer argument?

I was recently introduced to this mechanism of using a std::unique_ptr to implement a "generic" RAII mechanism: // main.cpp #include <memory> #include <sys/fcntl.h> #include <...
StoneThrow's user avatar
  • 5,426
0 votes
1 answer
164 views

How to use handle in WINAPI when I implement my c++ code with RAII principle? [duplicate]

What is the best way for using HANDLE object from WINAPI when I want to write my code consider RAII principle in c++ I write the following code: bool Uninstall(wstring folder, const bool removeDir = ...
Ohad Porat's user avatar
2 votes
1 answer
193 views

How can I wrap a C object in a custom RAII Class in C++?

I am using the library igraph and the library uses a lot of allocating and freeing memory using custom functions. I want to remove the possibility of forgetting to free memory by using RAII. The code ...
Tom McLean's user avatar
  • 5,638
-1 votes
2 answers
198 views

Initialize a string with a char pointer with zero-copy

Say I am given a long and null-terminated cstring as char* text_ptr. I own text_ptr and I am responsible of free()ing it. Currently, I use text_ptr and free() it each time after use. I try to improve ...
D.J. Elkind's user avatar
0 votes
1 answer
68 views

How do you handle large object copying with RAII?

i'm trying to wrap opengl textures into an RAII based object but I don't know how to handle copying when a RAII object is very expensive to copy. Here's an example of an expensive RAII object. class ...
Richard Bamford's user avatar
4 votes
0 answers
175 views

Python: how to manage a variable's lifetime beyond a single function?

I'm looking to better understand how Python can be used to guarantee resource release when the lifetime of the resource extends beyond a single function. The go-to answer for the general problem of ...
davidA's user avatar
  • 12.8k
0 votes
4 answers
144 views

What should I do if the 2nd malloc failed in the same constructor

Note that the basis of the question is to use two malloc()s...while suggesting not using malloc() at all is perfectly valid and leads to better design, this is not the point of the question. Perhaps ...
D.J. Elkind's user avatar
0 votes
1 answer
76 views

What are some C++ alternatives to static objects that could make destruction safer (or more deterministic)?

I'm working on a large code base that, for performance reasons, limits access to one or more resources. A thread pool is a good analogy to my problem - we don't want everyone in the process spinning ...
Josh A.'s user avatar
  • 384
-2 votes
1 answer
266 views

How to properly implement a vector of abstract class

I'm implementing a toy SQL database. In my code I'd like to have an abstract class Field and its two derived classes IntField and StringField. Also I'd like to have a Tuple class which represents a ...
Franciszek Malinka's user avatar
0 votes
0 answers
66 views

local variable scope vs lifetime -- is it guaranteed when the destructor is called?

This question is for understanding the effect of a class that's used for RAII; specifically if a variable of that class is allocated at the beginning of a function, is the destructor only called when ...
Peter Ludemann's user avatar
2 votes
1 answer
472 views

Is it a bad idea to acquire a lock in a destructor?

Say we have something along the lines of the following pseudocode, with the goal of achieving both concurrency and taking advantage of RAII: class Foo { public: vector<int> nums; mutex ...
walnut's user avatar
  • 23
0 votes
1 answer
104 views

Is it possible to know in a destructor that an r-value referrence is being deleted?

I was testing my own RAII pointer implementation that does some weird stuff (by design). To test it, I made a class that tracks constructors and destructors and makes sure everything is deleted and ...
Tomáš Zato's user avatar
  • 50.7k
6 votes
2 answers
606 views

`std::lock_guard` for `std::counting_semaphore` and `std::binary_semaphore`

Is there any RAII guard similar to std::lock_guard, std::scoped_lock or std::unique_lock provided by the standard which I can use in combination with std::binary_semaphore and std::counting_semaphore?
Vogelsgesang's user avatar
1 vote
0 answers
65 views

Idiomatically, should python context managers acquire resources at initialization, or when entered?

In general, I really like the explicitness of Python's context managers (CMs), but have been having trouble dealing with their inherent ambiguity. Specifically, without looking at a CM's code, it's ...
Aaron V's user avatar
  • 6,660
0 votes
2 answers
324 views

Asynchronous Destruction and RAII in C++

According to RAII when I destroy the object, its resources are deallocated. But what if the destruction of the object requires asynchronous operations? Without using RAII I can call close method of my ...
Кирилл Волков's user avatar
0 votes
0 answers
84 views

Why a class cannot has reference of a const char string? [duplicate]

I have these code and I found s will get invalid if it is a C-styled const string: class has_a_str_ref { const string& str; public: has_a_str_ref(string const& s) : str(s) {} void show(...
Pluveto's user avatar
  • 466
1 vote
1 answer
452 views

Locking an array of std::mutex using a std::lock_guard array

I have the following array of mutexes: std::mutex mtx[5]; And I would like to lock them all with an RAII style: std::lock_guard<std::mutex> grd[5] { mtx[0], mtx[1], mtx[2], mtx[3], mtx[4] }; ...
Nonyme's user avatar
  • 1,220
1 vote
2 answers
79 views

Does header initialization break RAII?

Consider the following C++ header: #include "OtherThing.h" class Thing { public: Thing(); //ctor private: OtherThing my_var_{}; }; Is the private var my_var_ still managed ...
tjcertified's user avatar
0 votes
1 answer
95 views

Intuition on C++ situations where an an unknown number of objects of a custom class will be needed at runtime

Everything below has to do with situations where a developer makes a custom C++ class (I have in mind something like OnlyKnowDemandAtRuntime below)... and there can be no way of knowing how many ...
tarstevs's user avatar
0 votes
2 answers
132 views

how to call destructor only once when fork

I wrote MmapHandler that provides a shared memory among processes using mmap and at destruction, it unmaps the shared memory. I want munmap to be called once by the parent process. However, this ...
MoneyBall's user avatar
  • 2,363
4 votes
1 answer
361 views

Why std::shared_ptr control block need to hold a pointer to managed object with its correct type

I am looking at the shared_ptr implementation in the following post. One question that is not entirely clear to me is, why in addition to the pointer stored with T* type in shared_ptr class itself, ...
Grigor Aleksanyan's user avatar
1 vote
0 answers
713 views

Vulkan-Hpp: What is the difference between vk::UniqueHandle and vk::raii wrappers?

I read the documentation of the new raii wrappers in the Vulkan-Hpp API. It seems that both vk::UniqueHandle<T> and the raii wrappers are move only objects that destruct their handle in their ...
Elad Maimoni's user avatar
  • 3,831
0 votes
1 answer
63 views

Restoring a C++ stream's exception mask for caller

I am writing a C++ function that takes a std::istream as an argument and reads from it to decode an image. When decoding the image, I want the stream to throw exceptions if some error occurs during ...
Azura's Starfish's user avatar
1 vote
1 answer
358 views

Does std::terminate() trigger stack unwinding?

I've been trying to implement Exception class, and for program termination i've decided to use std::terminate(), but i'm not suse whether or not std::terminate() triggers stack unwinding process. For ...
SoldatovAndrey's user avatar
1 vote
1 answer
745 views

RAII locking with condition

I have a piece of code which needs to be protected by a lock only if some condition is true. if(condition) { std::lock_guard<std::mutex> guard(some_mutex); // do a bunch of things } ...
0Nicholas's user avatar
  • 389
1 vote
1 answer
197 views

Concise RAII for Trompeloeil mocks

I have classes like this: /* "Things" can be "zarked", but only when opened, and they must be closed afterwards */ class ThingInterface { public: // Open the thing for exclusive ...
Inductiveload's user avatar
-2 votes
1 answer
280 views

RAII: do mutexes in a vector declared in a loop all unlock in the next iteration?

Suppose I have the following: // ... necessary includes class X { struct wrapper{ std::mutex mut{}; } std::array<wrapper, 20> wrappers{}; void Y() { for (auto i{0u}; i ...
SRSR333's user avatar
  • 182

1
2 3 4 5
12