2,176 questions
2
votes
1
answer
196
views
list<unique_ptr<int[]>> giving error use of deleted function [duplicate]
I need a list of unique pointers to ints (I need the underlying int arrays because of MPI compatibility, they are buffers that are getting tracked for work done). I have a workaround but would like to ...
3
votes
2
answers
125
views
Moving underlying container (std::vector or std::deque) for std::stack and std::queue [duplicate]
I had a usecase where I use a stack to process some data. Once processed, I want to output the data as a vector. But since underlying containers in stack are protected, it is now allowed to:
stack<...
1
vote
1
answer
232
views
Are swaps allowed to self-check?
While checking &other != this is generally not a good idea in move/copy assignment and the copy-and-swap idiom should be preferred, is it allowed for a swap to perform such a check?
Copy-and-swap ...
2
votes
2
answers
125
views
Why can I not efficiently move the strings when using std::istream_iterator<std::string>?
#include <fstream>
#include <string>
#include <vector>
int main() {
auto fin = std::ifstream("tmp.txt");
auto pos = std::istream_iterator<std::string>(fin);...
2
votes
1
answer
144
views
Using std::move with Constructor(Type t) or Constructor(Type&& t). What's the difference?
I'm studying std::move semantics and I would like this to be clarified to me:
Say I have:
// Message.h
class Message
{
private:
std::array<uint8_t, BUFFER_SIZE> buffer;
std::queue<...
1
vote
2
answers
101
views
making an invocable concept more accurate with respect to argument value category
As far as I understand, std::invocable<callable_type,args_type...> treats the callable arguments as rvalue references to the types args_type.
As a consequence, std::invocable<void(std::...
5
votes
2
answers
181
views
What is the rationale behind container types in std defining their own swap function even if their move-semantics have been correctly implemented?
Below is the most common implementation of std::swap:
template<typename T>
void std::swap(T& a, T& b) {
auto tmp = std::move(a);
a = std::move(b);
b = std::move(...
4
votes
1
answer
113
views
Clang-tidy bugprone-use-after-move with perfect forwarding
clang-tidy reports the following piece of code as bugprone-use-after-move
template <typename F, typename Tuple, size_t... I>
auto transform_tuple_impl(F&& f, Tuple&& tuple, std::...
2
votes
0
answers
116
views
MSVC calling deleted destructor when wrapping rvalue in struct (C++23)
I'm experimenting, with wrapping move semantics into a wrapper type:
#include <utility>
#include <type_traits>
// Type that will get moved
struct NonDestructible {
~NonDestructible() =...
2
votes
2
answers
139
views
Value categories in C++: What does "can be moved from" mean?
In C++, the value category of an expression is determined by two independent properties:
Whether the expression has an identity
Whether the expression can be moved from
(References: cppreference and ...
3
votes
1
answer
95
views
Doing std::move in constructors initialization segment
I have an issue with clang-tidys recommendation
Clang-tidy: arg is passed by value and only used once; consider moving it.
So the code is essentially this:
struct S{
kinda_heavy obj;
S(...
6
votes
1
answer
471
views
Is const T& effectively the same as T&& with std::forward for rvalue argument when be passed into another function?
Say I have a const T& version:
template <typename T>
void yetAnotherFunc( const T &input ) {
// do something...
}
template <typename T>
void myFunc( const T &input ) {
...
6
votes
1
answer
227
views
Static assertion failed: result type must be constructible from input type when moving objects into std::vector
I'm experimenting with move semantics in C++, and I have a simple class Entity that should only be movable — copying is disabled.
Here’s the class:
class Entity {
public:
//...
Entity() = ...
-1
votes
1
answer
70
views
How do I move a Sender object out of a mutable reference to a Vector of tuples of Strings and Sender Objects?
This is not a solution to my problem. The suggested answer replaces the values with Nones. I quite literally require the size of my vector to reduce.
MRE:
use tokio::sync::mpsc;
#[tokio::main]
async ...
26
votes
3
answers
2k
views
Only copiable type not accepted in msvc std::vector implementation
In the following code:
struct copy_only
{
copy_only() = default;
copy_only(const copy_only&) = default;
copy_only& operator=(const copy_only&) = default;
...
1
vote
0
answers
94
views
Why is the string& overload called instead of string&&? [duplicate]
Why is the output of the below code a reference: foo and not moved: foo?
#include <iostream>
void process(std::string& v) {
std::cout << "reference: " << v <<...
3
votes
1
answer
136
views
Why does adding std::move bring the capture back to the stack?
Given the following code that tries to allocate a lambda capture on the heap:
#include <array>
int test(void) {
//auto big_lambda = new auto([d = std::array<int, 1024>{5,1,2}]() { ...
4
votes
3
answers
207
views
Copy constructor called when pushing object onto std::vector
#include <iostream>
#include <vector>
class Car{
public:
int weight;
Car(int weight): weight(weight){
};
Car(const Car& other){
std::cout<<&...
6
votes
2
answers
227
views
Can a moved from object be moved again?
In C++, a moved object is left in a valid but unspecified state, which is basically a way to say you can assign to it and destroy it. But, can the object also be copied and moved?
For example, if I ...
1
vote
0
answers
88
views
In my custom string class, can I have a special behavior if `substr` assigns to self?
I have a very simple fixed-buffer string class. I am targeting embedded and don't want dynamic allocations. I am including it for reference, but the question is more general.
template <auto ...
4
votes
1
answer
205
views
How can I use `.value()` on `std::expected<T, E>` where `T` is a move-only type?
The following code:
#include <chrono>
#include <expected>
#include <stdexcept>
#include <string>
#include <thread>
#include <utility>
using namespace std::literals;...
1
vote
3
answers
93
views
How not to capture or move a String in a match branch or ok_or argument
I'm working on a function that converts a json value into an i32, returning an error if any step of the conversion fails.
fn json_to_block_height(height: Value) -> Result<i32, RPCError> {
...
2
votes
1
answer
158
views
Confused about returning std::unique_ptr
So say I have a tree structure, with a node defined like:
struct Node
{
byte key_part;
unique_ptr<Node> left, right, middle;
TValue value;
};
unique_ptr<Node> root;
The ...
2
votes
0
answers
103
views
Is there a reason for the lack of vector's (and other sequential containers such as deque) constructor that moves an element to perfom one less copy?
Inspecting the constructor std::vector::vector( size_type count, const T& value, const Allocator& alloc = Allocator() );(ref), we can read that it:
Constructs a vector with count copies of ...
2
votes
1
answer
98
views
Why does moving a const ref return value into another function still move-construct the object?
In the following example the function Table::get_subtable() is returning a const reference to an internal subobject (SubTable). This value is then std::moved and passed into a static factory function ...
3
votes
1
answer
85
views
Understanding why the move constructor is called in addition to the move assignment operator in Stroustrup's PPP?
I am reading through Programming: Principles and Practice in C++, 4th edition by Stroustrup and I am confused about the output of some code that is intended to illustrate the copy constructor/copy ...
3
votes
2
answers
144
views
Implementing bitwise swap for MyString
Is the following Move operations legit, as in there is no UB.
Instead of two swaps I want to implement a one swap of the 16 Bytes of MyString.
class MyString {
std::size_t size_;
char* str_;
...
5
votes
2
answers
510
views
Warning "bugprone-exception-escape" when captured object throws in copy constructor
When I have a C++ lambda that captures an object by value, and that object can throw an exception in its copy constructor, clang-tidy will show a warning:
warning: an exception may be thrown in ...
0
votes
1
answer
155
views
Should I `std::move` from the `std::future`?
Let's say I have a function that returns a std::vector, and I want to call it asynchronously.
std::vector<int> foo(int n);
int main() {
auto future_vector = std::async(foo, 999);
// ... ...
-1
votes
2
answers
236
views
How to use move semantics in a loop and avoid copying?
I created a little parser and would like to make the looped part as fast as possible. Thus I would like to avoid copying using move semantics instead. But I can't understand how to combine move ...
1
vote
0
answers
77
views
Class jthread in C++20 supports proper move semantics
I'm reading the "C++20 for Programmers An Objects-Natural Approach, 3rd Edition" and came across a paragraph in the book that discusses several features of std::jthread, specifically:
"...
1
vote
2
answers
112
views
Extracting a std::unique_ptr member using std::move(), from a class that is invalid when null: how to avoid invisibly making object invalid?
Consider the following scenario.
We have a class bar that owns a foo data object via a unique pointer. A bar must always be constructible into a valid state; that is, bar must always own some data, so ...
6
votes
0
answers
62
views
How to use std::move when dealing with universal refernce parameters being passed to a function/method [duplicate]
In the following code, which of the assignment to handler is correct or are they both equivalent to each other
#include <string>
#include <functional>
struct mything {
using handler_t =...
1
vote
1
answer
147
views
move assignment argument throws error when dereferenced but works when member accessed directly
In the minimum needed code snippet, in the move assignment, why is the commented line *arg = nullptr; illegal and arg.p = nullptr; okay? If I understand correctly, both are modifying rvalue, yet on ...
1
vote
1
answer
135
views
In C++, what happens under the hood when an rvalue of a move-only type is passed to a function by value?
I am trying to understand value categories in C++ a bit better, and I encountered some code that got me a bit confused.
I looked at some questions such as Accept move-only parameter by value or rvalue ...
4
votes
2
answers
274
views
Move objects from a set to another set with a different comparison functor
I have a large number of large objects in my program. They are currently stored in an std::set with a customer comparison functor. The set starts empty and I keep emplacing objects into it. I also ...
2
votes
2
answers
185
views
pushing a unique_ptr into a vector of variant unique_ptr
I am playing around with C++ and faced this problem.
If I have a variant that looks like this:
using Fruit = variant<Apple, Tomato>
and a vector of unique_ptr of Fruit:
vector<unique_ptr<...
3
votes
2
answers
178
views
Use after move in function call
When exactly does an object cast with std::moved get moved?
For instance, does the following code constitute use after move?
f(std::move(a), a.Something())
Where f = f(A a, int x) and a is an ...
1
vote
1
answer
57
views
Is boost type_erasure::any allocation on move avoidable?
When I move a boost::type_erasure::any object like in this test case:
#include <boost/type_erasure/any.hpp>
#include <string>
int main() {
typedef ::boost::mpl::vector<
...
2
votes
1
answer
497
views
Does Rust's move semantics involve copying data? [duplicate]
I am curious about the "move semantics" in Rust and whether data is copied when ownership is transferred. Here's some demo code:
#[derive(Debug)]
struct Foo {
name: i32,
age: i32,
}
...
0
votes
1
answer
99
views
Why does moving a variable into a spawned thread pass the borrow checker even when not copied? Doesn't that mean it uses a pointer to the original?
I have this code but I do not understand why it compiles:
use std::thread;
use std::time::Duration;
struct State {
value: u32,
}
impl State{
pub fn new() -> State{
State{ value: 0 }...
2
votes
0
answers
92
views
Returning a moved parameter on failure
Is it an acceptable pattern to return a moved function parameter in case some kind of problem occurred? For example when trying to store data in a database, but validation failed and the data handle ...
6
votes
2
answers
253
views
Modern ways to implement assignment for value types
This question is about how to implement assignment in modern C++ value types, with the goal of avoiding misleading code or code that is inconsistent with built-in behavior.
In C++, generated values (...
0
votes
0
answers
69
views
Move semantic: Why does the return statement call the copy constructor, when the parameter is an rvalue reference? [duplicate]
Consider the following code:
class Widget {
public:
Widget() {
std::cout << "\nCtor";
}
Widget(const Widget& obj) {
std::cout << "\nCopy ctor&...
3
votes
2
answers
586
views
C++ move semantics on returned value
In term of move semantics on return value, I heard that the best practice is to return the object as is, and don't call std::move to it, as it prevent return value optimizations. However, consider the ...
0
votes
0
answers
114
views
Does the Copy and Swap idiom have a not-required swap?
In an answer to this question, under the label: "Why does that work?" , it was noted that:
Now, if other is being initialized with an rvalue, it will be move-constructed. Perfect. In the ...
14
votes
2
answers
584
views
Moving after copying in assignment of conditional operator result
Simplified program as follows
struct S {
S() {}
S(const S &) {}
S(S &&) = delete;
};
S x;
S y = false ? S() : x;
is accepted just fine by GCC and Clang, but the latest Visual ...
0
votes
2
answers
139
views
Is there a standard function for performing a move-or-copy in c++?
I have a function which takes an rvalue reference:
void foo(int&& x);
I would like to create another function which supplies a universal interface with the original function:
template <...
1
vote
2
answers
133
views
Error: Use of moved value, while it cannot be used
Consider the following code:
fn print_or(opt: Option<()>, tail: Vec<i32>) -> Vec<i32> {
opt.map_or(tail, |_| {
println!("{:?}", tail);
tail
})
}
...
1
vote
1
answer
129
views
C++ passing a string to class setter function [duplicate]
I see this subject was discussed in StackOverflow, but I could not find the right answer.
I've been using C++ for many years, and I am still in doubt about how to write a simple setter method for a ...