c++11,move,encapsulation,rvalue-reference,push-back , R-value Reference push_back Function

R-value Reference push_back Function


Tag: c++11,move,encapsulation,rvalue-reference,push-back

I'm writing a Queue class. I have two versions of push_back for the new C++11 standard. One of these versions uses a rvalue reference as a parameter. My version works, but I think it must be lacking something:

 97 template <typename T>
 98 void Queue<T>::push( T && val ) 
 99 {
100     c.push_back( val );
101 }

It seems I should have used std::move, but I'm not sure how to implement this. c in the above function refers to a deque object encapsulated in my Queue class. Any help understanding what I should do to construct this function appropriately would be much appreciated!


Yes, you need std::move here, but you could also use emplace_back here:

template <typename T>
void Queue<T>::push( T && val ) 
     c.emplace_back( std::move(val) );


std::push_heap and std::pop_heap with MoveConstructible objects

I want to maintain a heap where the payloads are MoveConstructible (because they hold a std::unique_ptr inside.) Although the documentation suggests that the object must be MoveAssignable and MoveConstructible, doing so throws an error both in GCC and Clang. Sample Code I don't use an std::unique_ptr yet, but just disable...

Can't compile C++11 source using GCC 5.1 toolchain

I'm trying to compile a library written with C++11 features using GCC 5.1 on Ubuntu. However, it complains std::unique_ptr is not defined. gcc (Ubuntu 5.1.0-0ubuntu11~14.04.1) 5.1.0 g++ (Ubuntu 5.1.0-0ubuntu11~14.04.1) 5.1.0 CXX flags: -std=c++11 -Wall -Wextra -Weffc++ -pedantic Output: error: ‘unique_ptr’ in namespace ‘std’ does not name a template type std::unique_ptr<...

Alias the return type of a const overloaded function

I have the following overloaded function : template<size_t N, typename T> auto get(const T & _t) -> decltype(std::get<...>(_t)) { ... } template<size_t N, typename T> auto get(T & _t) -> decltype(std::get<...>(_t)) { ... } First question is : does the first one uses std::get(const tuple<_Elements...>& __t) and the second one...

I think assigning JsonValue values to JsonValues might be very slow, in comparison to having a Value be a key

Json::Value is located in: #include <json/value.h> I have a result Json::Value object being created which will be pushed back to the user. The issue with it is that it takes a super long time to complete, which boggles my mind. I think that there is something off with Json::Value, maybe...

Finding all keys that correspond to same value in std::unordered_map

I have an unordered_map looking like this: std::unordered_map<int, std::string> theMap2 = {{1,"a"}, {2,"b"}, {3,"c"}, {4,"a"}}; I want to find all the keys that have same value lets say 1. Any suggestions beside the obvious way: std::vector<int> arrKeys; std::string value = "a"; for (const auto& element : theMap) if (element.secont ==...

C++ error: deduced conflicting types for parameter 'T' string vs const char *

So, I am writing a simple, templated search function for deque container. Here's the code: template <typename T> void searchInDequeFor(std::deque<T> Deque, T searchValue) { for(const auto & element : Deque) { if(Deque.empty()) { std::cout << "Deque is empty, nothing to search for..." << "\n"; } else if(element==searchValue) { std::cout <<...

Atomic/not-atomic mix, any guarantees?

Let's I have GUI thread with code like this: std::vector<int> vec; std::atomic<bool> data_ready{false}; std::thread th([&data_ready, &vec]() { //we get data vec.push_back(something); data_ready = true; }); draw_progress_dialog(); while (!data_ready) { process_not_user_events(); sleep_a_little(); } //is it here safe to use vec? As you see I not protect "vec" by any kind of...

Dereferencing a temporary 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....

Reordering vector of vectors based on input vector

In a small application, I've been using a std::vector of std::vector<std::string> to temporarily store some data (pulled from a non-SQL database) before processing it and uploading it to a SQL database. Unfortunately, the API from which I am extracting the data does not necessarily return fields in the order specified...

Call template function for the value of a pointer out of a template function, in C++

I am trying to call a template function for the pointer that was given as template parameter in my calling function. My code is: template <> struct serialize_helper<std::string> { // not important code... } }; template <class T> inline void serializer(const T& obj, StreamType::iterator& res) { if(std::is_pointer<T>::value) { //THIS doesn'...

syntax for calling a method on a member with multiple instances

I the following case template<typename T> class base{ public: void test(){} }; template<typename T> class helper{ public: base<T> t; }; template<typename T, typename ... Ts> class holder: public helper<T>, helper<Ts>... { }; int main(int argc, char *argv[]){ holder<int, short, long> h; h.t.test(); // of course, error here } Which compiles...

Why is initialization of enum class temporaries with arbitrary values allowed?

I came across some code like the following in one the CppCon 2014 talks that confused the heck out of me. The audience accepted it without comment, so I presume that it's legal: enum class Foo { Bar }; Foo const v1 = Foo(5); The question is: why does this...

Why is my code failing to compile? (perfect forwarding and parameter packs)

Here is the program: #include <memory> struct A; struct B { void fn(A* ptr) {} }; template<typename ...Args> void foo(B* b, void (B::*func)(Args...), Args&&... args) { (b->*func)(std::forward<Args>(args)...); } struct A { void bar() { B b; foo(&b, &B::fn, this); } // fails }; int main() { A a; B b;...

Error with stoi and debugged with gdb [closed]

My OS is ubuntu 14.04, laptop, i7. The g++ version is g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2. I tried to run a simple code to test stoi: #include <string> int main() { std::string s = "123"; int i = std::stoi(s); } When I compile it with: g++ -g prueba2.cpp, I get: prueba2.cpp:...

Issue using std::atomic_flag with worker thread

sorry for the verbosity - I did my best to condense my code sample into a minimally functional class and main() method. I'm trying to use an atomic_flag to notify _rx() within my worker thread to quit when stop() is called. I believe the issue is in trying to create...

In c++11 what should happen first: raw string expansion or macros?

This code works in visual c++ 2013 but not in gcc/clang: #if 0 R"foo( #else int dostuff () { return 23; } // )foo"; #endif dostuff(); Visual C++ removes the if 0 first. Clang expands the R raw string first (and never defining dostuff). Who is right and why?...

Simple thread/mutex test application is crashing

I wrote a simple test program which accumulates random samples to a buffer using multiple threads. Each thread uses a stack for reducing the mutex waits. This is for investigating problems in a much larger program. The code currently crashes on mingw-w64 4.9.2 Any idea why? Debugging halts on "signal-received"...

How can I simulate a nested function without lambda expressions in C++11?

I have the following code: int main(int argc, char **argv) { App app(800, 600); app.add_event_scene(Scene("Event Plot", event_plot)); Image x("sample.png"); struct foo { static void visual_plot() { x.draw(); } }; // Error. app.add_visual_scene(Scene("Visual Plot", foo::visual_plot)); app.run(); return 0; } And I get the following error: ||=== Build: Debug in Joy-Plus-Plus (compiler:...

Setting the content of a std::stringstream with str(const char*) has strange consequences

I use std::stringstream extensively to generate code. I have run into some querious behavior when setting the content with the str() function followed by using the operator<<. Can someone explain this behavior to me. I would very much appreciate it - Thanks. Example One: std::stringstream ssa; ssa.str("Setting string"); std::cout <<...

Junk varchar entries in MSSQL database using ODBC

I'm trying to insert a string-variable into a varchar(100)-field, but if the string is longer than 15 elements only junk is inserted (e.g. "0‰?"). First my setup: Development: Win7 (64bit) / VS2013 / C++11 / 64bit Application Database: Win8 (64bit) / Microsoft SQL Server Express 2014 (64bit) Driver: SQL Server...

Is there a syntax for incomplete nested type without a forward declaration?

The following program produces a diagnostic error. #include <memory> class Containing { // class Nested; // [1]: This line seems required. typedef std::shared_ptr<class Nested> Ptr; class Nested { Ptr & ptr (); void foo (const Ptr &p) { p->ptr() = ptr()->ptr(); // [2]: Error here without [1] } }; };...

How to match one of multiple alternative patterns with C++11 regex [duplicate]

This question already has an answer here: Strange results when using C++11 regexp with gcc 4.8.2 (but works with Boost regexp) [duplicate] 1 answer With Perl, the following results in a match: echo xyz | perl -ne 'print if (/.*(yes|no|xy).*/);' I'm trying to achieve the same thing with a...

std::move to a function

I have this example code: #include <iostream> class Struct { public: Struct() { std::cout << "0" << std::endl; } Struct(Struct&) { std::cout <<"1"<<std::endl;} Struct(const Struct&) { std::cout << "2" << std::endl; } }; class Struct2 { public: Struct s; Struct2() {} void setMember(const Struct& aux) { s = aux; }...

C++ operator []

I am trying to implement the operator [] that is to be used once for Set and once as Get, i need to differentiate between the two cases, as in the case of get, i need to throw an exception if the returned value is equal to -1; whereas in...

I can't download images uploaded ​​with “move_uploaded_file()” code on filezilla

When I use move_uploaded_file() code everything works fine and my files are being moved to my server. But later if I want to download those files from my server using filezilla, it says: "Could not start the transfer process" But i can download other files crate with imagejpeg() code. So...

Same function with and without template

I am trying to understand a piece of code of C++11. A class contains 2 functions as shown below: class abc { public: void integerA(int x); template<typename typ> void integerA(typ x); }; I am unable to understand benefit of declaring 2 same functions. Why not declare only one template function?...

Win7 Batch File - Moving Subfolders(& Files) to Grand-Parent Directory

I have a somewhat complicated problem. I've downloaded an archived website from archive.org using Httrack and now I have thousands of subfolders and files I need to merge before I can rebuild it. I'm trying to write a batch file to solve the problem. But my search results never come...

Implicit use of initializer_list

§[dcl.init.list] 8.5.4/2: The template std::initializer_list is not predefined; if the header <initializer_list> is not included prior to a use of std::initializer_list — even an implicit use in which the type is not named ( — the program is ill-formed. Does that mean this program is ill-formed? #include <vector> int main()...

Is executing C++ code in comments with certain Unicode characters allowed, like in Java?

I know that executing Java code in comments with certain Unicode characters is allowed. Please see this question for further clarification Executing Java code in comments. So was just curious to know if C++ has such features?

“Emulating” std::declval issues. Works (kind of) in g++, fails to compile in clang++

Trying to better understand std::declval, I came up with the following "toy model" code: #include <iostream> #include <typeinfo> struct Bar { Bar(double); // some non-default ctor double f(); // some function of which return type we want to get }; using Barref = Bar&&; // emulating std::declval<Bar>() int main() {...

Why is the boolean value within a structure within a vector not being updated?

This might sound like a very basic question, but I have trying to fix a simple bug for over an hour now and I can't seem to understand what's happening. I have the following structure declaration in my header file: struct StudentBody { string name; Vec2 position; bool disabled; StudentBody(string...

Why is erasing via a const_iterator allowed in C++11?

As of GCC 4.9.2, it's now possible to compile C++11 code that inserts or erases container elements via a const_iterator. I can see how it makes sense for insert to accept a const_iterator, but I'm struggling to understand why it makes sense to allow erasure via a const_iterator. This issue...

Remove smallest non-unique value from vector

I have an unsorted vector of doubles (Actually objects with a double member which is used in this case). From this vector I need to remove the smallest non-unique value. However, it is not guaranteed that a non-unique value exists. It is allowed to sort the range. As always I...

Calling variadic template function with no args failing

Given the following code: #include <iostream> template <typename... Args> void foo(Args&&... bargs, Args&&... aargs) { std::cout << "Hello" << std::endl; } int main() { foo<int, double>(1, 2.0, 3, 4.0); //OK foo<char>('c', 'd'); // OK foo(); //FAIL } I get the following compiler error: In function 'int main()': 15:9: error: no...

No match for 'operator*' error

Hello fellow programmers! I was going to write a small program for calculating total pay for different periods of time depending on the amount of hours and the salary that the user enters. I managed to make a small bit of the program but when I try to run it...

Sorting vector of Pointers of Custom Class

I have vector<FPGA*> current_generation_, which I'd like to sort by FPGA member fitness_ using the sort_members function. Applicable code follows: bool sort_members (FPGA* fpga_first, FPGA* fpga_second) { return (fpga_first->fitness() < fpga_second->fitness()); }; fpga.hpp #include <vector> class FPGA { public: explicit FPGA(int input_gates, int output_gates, int normal_gates); const int fitness(); protected:...

std::move on a C++ class does not move all members?

I understand that using v.push_back(std::move(foo)) will move foo contents to a vector. However I do not understand why the below code : #include <iostream> #include <vector> struct Foo { std::string s; float f; friend std::ostream& operator<<(std::ostream& stream,const Foo& foo) { stream << "{" << foo.s << ":" << foo.f <<...

Should checking loop conditions be counted towards total number of comparisons?

I have implemented three different sorting algorithms and now I want to confirm that my approach of counting the total number of comparisons is correct. In my mind, the number of comparisons shouldn't be tied to the conditional branches because if the condition isn't met, the comparison was still made...

How can I convert an int to a string in C++11 without using to_string or stoi?

I know it sounds stupid, but I'm using MinGW32 on Windows7, and "to_string was not declared in this scope." It's an actual GCC Bug, and I've followed these instructions and they did not work. So, how can I convert an int to a string in C++11 without using to_string or...

Call to implicitly-deleted copy constructor in LLVM(Porting code from windows to mac)

We are in the process of porting some c++ code from windows to mac and are having issues compiling it with LLVM 6.1 using c++11. We are encountering errors all over the place of "Call to implicitly-deleted copy contructor" Some of these errors are popping up in our code. for...

C++11 Allocation Requirement on Strings

I had heard that C++11 was going to require strings to be allocated in contiguous memory. I even thought I saw a stack overflow question on it, but I can't seem to find it. I know that in practice both gcc and Visual Studio do allocate strings contiguously, I'm just...

Camera calibration and conversion of coordinates(OpenCV)

I am trying to map the 2D pixel coordinates in an image to real world 3D coordinates with respect to a fixed webcam. The calibration tutorial on the OpenCV page (http://docs.opencv.org/doc/tutorials/calib3d/camera_calibration/camera_calibration.html) has given me the following xml file: <?xml version="1.0"?> <opencv_storage> <calibration_Time>"Wed Jun 17 12:02:01 2015"</calibration_Time> <nrOfFrames>25</nrOfFrames> <image_Width>640</image_Width> <image_Height>480</image_Height>...

Type function that returns a tuple of chosen types

I've implemented a type function Tuple that turn a list of My_enum values into an std::tuple of corresponding types: #include <tuple> enum My_enum{ t_int, t_double }; // Bind_type is a type function that given a My_enum returns the corresponding type template<My_enum E> struct Bind_type; template<> struct Bind_type<t_int>{ using type =...

Mapping const char * to duck-typed T at compile-time or run-time

I have many classes A, B, C, D, etc that are duck-typed and thus have the same methods and interface but do not inherit from the same class. E.g. class A { public: void foo(); void bar(); } class B { public: void foo(); void bar(); } class C {...

Sorting based on the rules set by a string variable

In my hypothetical app, I receive a list of hotels from the server. struct Hotel { std::string name; // e.g. Hilton, Ritz int stars; // In range [0..5], 0 stands for "unrated" int freeRoomCount; // Number of available rooms [0..N] int parkingPlacesAvailable; // Number of parking places availalble [0..M] }...

Passing something as this argument discards qualifiers

Using the below code, i get the following compile error: In static member function ‘static std::string ctedata::Record::getDispatcher<std::basic_string<char> >::impl(const ctedata::Record&, const string&)’: /home/jason/CrownTheEmpire/lib/ctedata/data.h:111:38: error: passing ‘const std::map<std::basic_string<char>, std::basic_string<char> >’ as ‘this’ argument discards qualifiers [-fpermissive] return rec.fieldValues_[field]; ^ In file included from /usr/include/c++/5.1.0/map:61:0, from...

How to re-write templated function to handle type deduction

So, I have this search function for the map container: template <typename Key, typename T> void searchInMapByKey(std::map<Key,T> Map, T keyValue) { if(Map.empty()) { std::cout << "Map is empty, nothing to search for..." << "\n"; } else { for(const auto & element : Map) { if(element.first==keyValue) { std::cout << keyValue <<...

C++ why does SFINAE fail with only a class template parameter?

I'm using SFINAE in the style of this answer in order to call a generic vector object by using an appropriate member function. For example, the following code calls operator[](int) const first, and if that doesn't exist then operator()(int) const: template<int I> struct rank : rank<I-1> { static_assert(I > 0,...

How can I pass unique_ptr into a function

How can I pass a unique_ptr into a function? Lets say I have the following class: class A { public: A(int val) { _val = val; } int GetVal() { return _val; } private: int _val; }; The following does not compile: void MyFunc(unique_ptr<A> arg) { cout << arg->GetVal() <<...