dimanche 31 juillet 2016

Use of Union with reference

At work I've been using linux and the GCC compiler for C++11 and C++14. In some of the code at work, I've used a union to store both a reference and a pointer, as so: (Simplified to just the important parts)

struct MyStruct
{
    //Stuff
    union { double& x; double* x_ptr; };
    MyStruct(double& value) : x(value) {}
    //More stuff
};

I believe this code is clear, readable, unambiguous, and provides a convenient way to store references which can be shifted to something else. It provides easily understandable syntactic sugar without costing performance while improving readability. When I attempted to use code like this in visual studio 15, however, the code failed to compile due to "an illegal union member of type double&".

  1. Is this code illegal under the standard, or just under Visual Studio 2015?
  2. Can I MAKE it compile in Visual Studio 2015, or submit a bug report/change request/something?
  3. Is use of a union in that way bad practice?

Note: At my work, pretty much all code is written for Linux and compiled with GCC, and for my specific project, C++11 is guaranteed and GCC is the only compiler that's going to be used.

tuple of void member functions

I'm attempting to create a tuple which contains a pointer to a void member function, but I'm having trouble making it work. here's my code:

class A
{
    void dostuff(){ cout<<" doing stuff "}
};

class B
{
    A* aobj;
    typedef vector<vector<tuple<int,int,void(A::*)()>>> sequence;

    sequence Sequence;

    void getinfo(int n1, int n2, void(A::*func)())
    {
        Sequence.resize(1);
        Sequence[0].push_back(make_tuple(n1,n2,(aobj->*func)()))//<--ERROR HERE
    };
};

it's giving me the error "invalid use of void expression." I also tried to simplify the function to :

void getinfo(void(A::*func)())
{
    make_tuple((aobj->*func)());
}

and it still gives me the same error.

Cereal: how to manage the implementation struct for the PIMPL idiom

I am having troubles to use cereal with the PIMPL idiom.

This is a minimal example:

b.h

#ifndef _B_H_
#define _B_H_

#include <memory>
#include "cereal/types/memory.hpp"
#include "cereal/archives/json.hpp"

struct BImpl;

class B
{
public:
    B();
    ~B();

private:
    std::unique_ptr<BImpl> _impl;

    friend class cereal::access;

    template <class Archive>
    void serialize( Archive& ar )
    {
        ar( CEREAL_NVP( _impl ) );
    }
};

#endif

b.cpp

#include "b.h"

struct BImpl
{
     int b_i = 0;

private:
    friend class cereal::access;

    template <class Archive>
    void serialize( Archive & ar )
    {
        ar(
            CEREAL_NVP( b_i )
          );
    }
};

B::B() : _impl( new BImpl )
{
}

B::~B()
{
}

main.cpp

#include "b.h"
#include <fstream>
#include "cereal/archives/json.hpp"

using namespace std;

int main( int argc, char** argv )
{
    B b1;
    {
        std::ofstream file( "out.json" );
        cereal::JSONOutputArchive archive( file );
        archive( CEREAL_NVP( b1 ) );
    }
}

And here the errors that I get on MSVC 2015 Community Edition when I try to compile the minimal example:

  • C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\type_traits(428): error C2139: 'BImpl': an undefined class is not allowed as an argument to compiler intrinsic type trait '__is_polymorphic'

  • C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\type_traits(435): error C2139: 'BImpl': an undefined class is not allowed as an argument to compiler intrinsic type trait '__is_abstract'

I am quite sure that I am not the first attempting to do this, but I have not been able to find nothing specific in the documentation or code snippets with a working solution.

CRTP. Trying to understand an given example

While I was trying to understand CRTP, I came across this example, where it is a bit fuzzy to me. I can achieve the same results if I do something simpler like this:

#pragma once
#include <iostream>
template <typename T>
class Base
{
public:
    void method() {
        static_cast<T*>(this)->method();
    }
};

class Derived1 // : public Base<Derived1>   <-- commented inherintance
{
public:
    void method() {
        std::cout << "Derived1 method" << std::endl;
    }
};


class Derived2 // : public Base<Derived2>   <-- commmented inherintance
{
public:
    void method() {
        std::cout << "Derived2 method" << std::endl;
    }
};


#include "crtp.h"
int main()
{
    Derived1 d1;
    Derived2 d2;
    d1.method();
    d2.method();
    return 0;
}

My question is: what is the purpose of CRTP here? After thought a bit I guess this use is to allow something like this:

template<typename T>
void call(Base<T>& x)
{
    x.method();
}

and call it like this

int main()
{
    Derived1 d1;
    Derived2 d2;

   call(d1);
   call(d2)
}

Am I correct?

Binary file into STL char array

I am trying to read a binary file into a STL Vector of chars. I have used the following link as reference: reading the binary file into the vector of unsigned chars

I also converted this in MATLAB and the results the I got in MATLAB were 83 84 1 1 0 0 0 0 0 0 0 184 21 176 221 14 248 4

But the results of the above C++ implementation are S T ..........

I understood that 83 -> S, 84 -> T but how do I get the output like that of MATLAB?

Thanks

Are C++ distributions keep or update parameters on op(URNG, params)?

Question to C++ language lawyers, applicable to pretty much any distribution (normal, uniform, poisson, ...), but I'll use Poisson as an example.

Simple code

#include <random>

std::default_random_engine rng;

double lambda = 5.0;
std::poisson_distribution<int> Poisson(lambda);

auto A = Poisson(rng);      // call with lambda equal to 5
auto B = Poisson(rng, 3.0); // call with lambda equal to 3
auto C = Poisson(rng);      // call with lambda equal to what?

What lambda would be used in case of C?

All distribution have the same overloaded operators:

template<class URNG> result_type operator()(URNG& g);
template<class URNG> result_type operator()(URNG& g, const param_type& parm);

If we construct distribution with one set of parameteres, then call second op(), will distribution state altered? Or it will use parameters from the constructor?

C++ class method reimplementation

Is there any way to tell to the compiler that not compile a method of parent class, but compiles the same method in the child class?. May be confusing my question, My app will be released in two versions: regular and demo. In demo version I want to remove/reimplement a method from the base class (the base class is from a framework), so:

class FromLibrary
{
public:
   ...
   void addProperty (Property* p) 
   {
       Some stuff with property, is used to save in files, etc...
   }
   ...
};

class MyClass : public FromLibrary
{
   #ifdef DEMO
   void addProperty (Property* p) {};
   #endif    
};

Ok, it works, but maybe a cracker can change the method address to point to "FromLibrary::addProperty"

Note: "FromLibrary" is not a static/dynamic lib, but I don't want to modify it, to keep updated without modify my own version

UTF conversion functions in C++11

I'm looking for a collection of functions for performing UTF character conversion in C++11. It should include conversion to and from any of utf8, utf16, and utf32. A function for recognizing byte order marks would be helpful, too.

How to get all parameters' types from parameter pack?

I have the following piece of code where I define struct quick with templated static method random with some specializations:

( I used function_traits from other SO answer. Attached on the bottom for reference.)

struct quick
{
  template <typename T>
  static T random();

  template <typename F>
  static void check(F f)
  {

    constexpr auto arity = function_traits<F>::arity; // easy :)
    std::cout << arity << std::endl;
    typedef typename function_traits<F>::template arg<0>::type type0; // easy:)
    // how to get all types of all F's parameters?
  }
};

template <>
std::string quick::random<std::string>()
{
  return std::string("test");
}

template <>
int quick::random<int>()
{
  return 1;
}

I would like to get all types of F's parameters inside check so that I can generate a tuple with random entries (based on my random method specializations).

I tried with something like:

template<typename F, typename ...TIdxs>
using ArgTypes = typename function_traits<F>::template arg<TIdxs>::type...;

// ...
// inside check

typedef ArgTypes<F, std::make_index_sequence<arity>> types;

but failed miserably:

main.cpp:80:72: error: expected ‘;’ before ‘...’ token
 using ArgTypes = typename function_traits<F>::template arg<TIdxs>::type...;
                                                                        ^
main.cpp: In static member function ‘static void quick::check(F, D)’:
main.cpp:98:15: error: ‘ArgTypes’ does not name a type
       typedef ArgTypes<F, std::make_index_sequence<arity>> types;


I have used function traits utilities from this SO answer.

template <typename T>
struct function_traits : function_traits<decltype(&T::operator())>
{};
// For generic types, directly use the result of the signature of its 'operator()'

template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const>
// we specialize for pointers to member function
{
    enum { arity = sizeof...(Args) };
    // arity is the number of arguments.

    typedef ReturnType result_type;

    template <size_t i>
    struct arg
    {
        typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
        // the i-th argument is equivalent to the i-th tuple element of a tuple
        // composed of those arguments.
    };
};

Reading contents of file into dynamically allocated char* array- can I read into std::string instead?

I have found myself writing code which looks like this

// Treat the following as pseudocode - just an example

iofile.seekg(0, std::ios::end); // iofile is a file opened for read/write
uint64_t f_len = iofile.tellg();

if(f_len >= some_min_length)
{
    // Focus on the following code here
    char *buf = new char[7];
    char buf2[]{"MYFILET"}; // just some random string
                            // if we see this it's a good indication
                            // the rest of the file will be in the
                            // expected format (unlikely to see this
                            // sequence in a "random file", but don't
                            // worry too much about this)
    iofile.read(buf, 7);

    if(memcmp(buf, buf2, 7) == 0) // I am confident this works
    {
        // carry on processing file ...
        // ...
        // ...
    }
}
else
    cout << "invalid file format" << endl;

This code is probably an okay sketch of what we might want to do when opening a file, which has some specified format (which I've dictated). We do some initial check to make sure the string "MYFILET" is at the start of the file - because I've decided all my files for the job I'm doing are going to start with this sequence of characters.

I think this code would be better if we didn't have to play around with "c-style" character arrays, but used strings everywhere instead. This would be advantageous because we could do things like if(buf == buf2) if buf and buf2 where std::strings.

A possible alternative could be,

// Focus on the following code here
std::string buf;
std::string buf2("MYFILET"); // very nice
buf.resize(7); // okay, but not great
iofile.read(buf.data(), 7); // pretty awful - error prone if wrong length argument given
                            // also we have to resize buf to 7 in the previous step
                            // lots of potential for mistakes here,
                            // and the length was used twice which is never good
if(buf == buf2) then do something

What are the problems with this?

  • We had to use the length variable 7 (or constant in this case) twice. Which is somewhere between "not ideal" and "potentially error prone".
  • We had to access the contents of buf using .data() which I shall assume here is implemented to return a raw pointer of some sort. I don't personally mind this too much, but others may prefer a more memory-safe solution, perhaps hinting we should use an iterator of some sort? I think in Visual Studio (for Windows users which I am not) then this may return an iterator anyway, which will give [?] warnings/errors [?] - not sure on this.
  • We had to have an additional resize statement for buf. It would be better if the size of buf could be automatically set somehow.

Possible msvc/intellisense bug with variadic template arguments

I am using VS2015 Update 3. The following piece of code gives an intellisense error on the lines in main(), however the code compiles and runs without error.

#include <iostream>
#include <tuple>

// Template parameter classes
template<class...> struct ComponentList {};   
template<class...> struct Filter {};
template<class...> struct FilterList {};

template<typename ATuple, typename BTuple>
class EntityManager;

template<class... A, template<class> class... B>
class EntityManager<ComponentList<A...>, FilterList<B...>>
{
public:
    template<class A>
    void test()
    {
        std::cout << typeid(A).name() << std::endl;
    }

    // Create tuple for each filter inside filterlist
    std::tuple<B...> tuples;
};

using MyComponents = ComponentList<int, double, float>;
using FirstFilter = Filter<int, double>;
using SecondFilter = Filter<float>;
using MyFilters = FilterList<FirstFilter, SecondFilter>;

void main()
{
    EntityManager<MyComponents, MyFilters> em;
    em.test<int>();
}

On the first line of main, intellisense says 'incomplete type is not allowed'.

On the second line, intellisense gives three errors: 'incomplete type is not allowed', 'type name is not allowed', and 'expected an expression'

Is this a bug in the compiler or in intellisense?

noexcept keyword is not supported by msvc in 2016

I am asking this question because I just can believe that it is 2016 and msvc compiler still does not support noexcept keyword. The following simple code:

class Test
{
public:
    Test()noexcept
    {
    }
};

Generates this error: error C3646: 'noexcept' : unknown override specifier

This code compiles by Visual Studio on Win32 platform, but it generates this error when I am trying to compile it on UWP. Am I missing something obvious or are they using different c++ compilers for Win32 and UWP? I am using Microsoft Visual Studio Community 2015 Update 3. Version 14.0.25424.00.

string passed from C++ to C# prints blank

#ifdef SERVER_TCP_EXPORTS
class __declspec(dllexport) Sock_Server
#else
class __declspec(dllimport) Sock_Server
#endif
{
public:
    int Server(const char* strErr,int bufSize);
    ...
 }

cpp file
int Sock_Server::Server(const char* strErr,int bufSize)
{
   // do something and assign the string to strErr
   (say) strErr = "Hello World";
   return -1;
}

in C#
[DllImport("Hello.dll", EntryPoint = "Server" CallingConvention = CallingConvention.StdCall)]

private extern static int Server(StringBuilder strErr, int bufSize);

public static int Connect(StringBuilder strErr, int bufSize)
{
   int res = Server(strErr,bufSize);    /// when the calls come here, strErr is empty
    return res;          // res has the value  -1
}

private void Form1_Load(object sender, EventArgs e)
{
   int res = 0;
   int bufSize = 4096;
   StringBuilder strErr = new StringBuilder(bufSize+1);

   res = Connect(strErr, bufSize); //when the calls come here, strErr is empty
    MessageBox.Show(strErr.ToString());   // it has the value -1
}

I am not a C# guy.I did some reading before posting this out,and tried all the possible combinations but some reason it didn't work.I am using Visual Studio 2013.I have couple of Q

[Q1] When I did MessageBox.Show(strErr.ToString()); in my C#, it just prints a blank string! Would really appreciate if anyone can help me as I am pretty new to all this.

[Q2] If I give EntryPoint ="Server" my code doesn't work.It complains,enrty point of Server is not found in Hello.dll. So,every time I have to find the exact entry in my dll using dumpbin.exe and then provide exactly how the compiler has created for me

[DllImport("Hello.dll", EntryPoint = "?Server@Sock_Server@@QAEHPBDH@Z" CallingConvention = CallingConvention.StdCall)]

Is there a better way of doing this.This is making the code cupled

[Q3] Is there a way to call C++ constructor/destructor.I do need to call both of them.I have called C'tor through some other method,I know that's not a good idea.Any help would be appreciated.

Thanks.

error: "expected an expression" I am trying to use array in function

void phage :: evaluate(bacteria ba[]) {

    for (int i = 0; i<popsize; i++)
        for (int j = 0; j<gensize; j++)
            fitness += m[i] == ba[i].m[j];
}

here is an evaluate function, declared in struct. when I try to call it, there is an error "expected an expression"

for (int i = 0; i < popsize; i++)
    population[i].evaluate(population[]);

finding the sum of the array when size is not given by the user,

Input The i-th line of the input contains an integer ai (0 ≤ a ≤ 1000) — the i-th element of the array. The size of the array is between 1 and 10, inclusive. Note that the size of the array is not given explicitly!

Output Output a single integer — the sum of the elements of the array.

I can't understand wired std::atomic_short.load() behavior

I check C++11 std::atomic_short behavior.
I set either 0 or 255 value to atomic_short variable.
But load() say value is neither 0 or 255.
I want atomic variable that one thread write and another thread read.

Environment:
Intel Core i5
OSX 10.11.6
clang (Xcode7.3.1)

#include <iostream>
#include <atomic>
#include <thread>

std::atomic_short value = ATOMIC_VAR_INIT(0);

void process1() {
    bool flag = false;
    for (int i = 0; i < 100000; ++i){
        std::this_thread::yield;
        if (flag){
            value.store(255);
        } else {
            value.store(0);
        }
        flag = !flag;
    }
}

void process2() {
    for (int i = 0; i < 100000; ++i){
        std::this_thread::yield;
        if (value.load() != 255 && value.load() != 0){
            printf("warningA! %d\n", i);
        }
    }
}

int main(int argc, char** argv) {
    value.store(0);
    std::thread t1(process1);
    std::thread t2(process2);
    t1.join();
    t2.join();

    return 0;
}


warningA! 3
warningA! 1084
warningA! 1093

xlib XNextEvent checking if a key is held down

I am using xlib to get keyboard input I want to simulate windows its getAsynckeystate() to check if a button is being pressed I tried using a timer to fix the result but its still broken. the function should always return true if 'z' is held down even if other keys are pressed or released at the same time (not working right now)

Code below

bool KeyboardState::keyPressed(Display* d, Window curFocus,int revert, Window root) {
XEvent ev;
XNextEvent(d, &ev);
clock_t startTime;
switch (ev.type) {
    case FocusOut:
        if (curFocus != root)
            XSelectInput(d, curFocus, 0);

        XGetInputFocus(d, &curFocus, &revert);
        printf("New focus is %d\n", (int) curFocus);

        if (curFocus == PointerRoot)
            curFocus = root;

        XSelectInput(d, curFocus, KeyReleaseMask | FocusChangeMask | KeyPressMask);
        break;

    case KeyPress:
        ks = XLookupKeysym(&(ev.xkey), 0);

        if (ks == XK_z) {

            keyState = true;
            startTime = clock();
        }
        break;
    case KeyRelease:
        if(ks == XK_z && startTime - clock() > 0){

        ks = XLookupKeysym(&(ev.xkey), 0);
            keyState = false;
        }
}
return keyState;
}

Is CppCoreGuidelines C.21 correct?

While reading the Bjarne Stroustrup's CoreCppGuidelines, I have found a guideline which contradicts my experience.

The C.21 requires the following:

If you define or =delete any default operation, define or =delete them all

With the following reason:

The semantics of the special functions are closely related, so if one needs to be non-default, the odds are that others need modification too.

From my experience, the two most common situations of redefinition of default operations are the following:

#1: Definition of virtual destructor with default body to allow inheritance:

class C1
{
...
    virtual ~C1() = default;
}

#2: Definition of default constructor making some initialization of RAII-typed members:

class C2
{
public:
    int a; float b; std::string c; std::unique_ptr<int> x;

    C2() : a(0), b(1), c("2"), x(std::make_unique<int>(5))
    {}
}

All other situations were rare in my experience.

What do you think of these examples? Are they exceptions of the C.21 rule or it's better to define all default operations here? Are there any other frequent exceptions?

samedi 30 juillet 2016

C++11 Segmentation Fault with Boost Polynomials

I am trying to implement euclidian polynomials gcd using boost library. It compiles. However, I got segmentation fault on the runtime.

This is my code:

polynomial<double> gcd_euclid(polynomial<double> const &a, polynomial<double> const &b){

polynomial<double> s, old_t = zero_element(std::multiplies<polynomial<double>>());
polynomial<double> old_s, t = identity_element(std::multiplies<polynomial<double>>()); 
polynomial<double> r = b; 
polynomial<double> old_r = a;

while (r != zero_element(std::multiplies<polynomial<double>>())) {

    polynomial<double> quotient = old_r / r;

    old_r = r; 

    r = old_r - quotient * r;

    old_s = s;

    s = old_s - quotient * s;

    old_t = t;

    t = old_t - quotient * t;
}

return old_r;

}

Using gdb, it traces the segfault to this part in the polynomial.hpp:

 template <class U>
 polynomial& operator *=(const polynomial<U>& value)
 {
  // TODO: FIXME: use O(N log(N)) algorithm!!!
  polynomial const zero = zero_element(std::multiplies<polynomial>());
  if (value == zero)
  {
      *this = zero;
      return *this;
  }
  polynomial base(*this);
  this->multiplication(value[0]);
  for(size_type i = 1; i < value.size(); ++i)
  {
     polynomial t(base);
     t.multiplication(value[i]);
     size_type s = size() - i;
     for(size_type j = 0; j < s; ++j)
     {
        m_data[i+j] += t[j];
     }
     for(size_type j = s; j < t.size(); ++j)
        m_data.push_back(t[j]);
  }
  return *this;

}

specifically this line:

 m_data[i+j] += t[j];

omit std::placeholders in std::bind

To create std::function, here is what I do:-

std::function<void(int,int,int)> f=
    std::bind(&B::fb,this,
        std::placeholders::_1,
        std::placeholders::_2,
        std::placeholders::_3
    );  

void B::fb(int x,int k,int j){} //example

It is obvious that B::fb receive three parameters.
To increase readability & maintainablity, I wish I could call this instead :-

std::function<void(int,int,int)> f=std::bind(&B::fb,this);  //omit _1 _2 _3

Question
Are there any features in C++ that enable omitting the placeholders?
It should call _1,_2, ..., in orders automatically.

I have googled "omit placeholders c++" but not find any clue.

Extracting string from text

I have a string My name is bob.I am fine I want to put each word and the '.' in a vector of strings How to do this using getline in c++?

Why can't I std::move std::unique_ptrs between std::sets?

I really want to move some unique_ptrs from one std::set into another:

#include <memory>
#include <algorithm>
#include <set>

int main()
{
   std::set<std::unique_ptr<int>> a;
   std::set<std::unique_ptr<int>> b;

   a.insert({0, std::unique_ptr<int>(new int(42))});

   std::move(a.begin(), a.end(), std::inserter(b, b.end()));
}

However, my GCC 4.8.5 on CentOS 7 is distinctly unhappy:

[root@localhost ~]# g++ test.cpp -std=c++11 -o test
In file included from /usr/include/c++/4.8.2/set:60:0,
                 from test.cpp:2:
/usr/include/c++/4.8.2/bits/stl_tree.h: In instantiation of ‘std::_Rb_tree_node<_Val>::_Rb_tree_node(_Args&& ...) [with _Args = {const std::unique_ptr<int, std::default_delete<int> >&}; _Val = std::unique_ptr<int>]’:
/usr/include/c++/4.8.2/ext/new_allocator.h:120:4:   required from ‘void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = std::_Rb_tree_node<std::unique_ptr<int> >; _Args = {const std::unique_ptr<int, std::default_delete<int> >&}; _Tp = std::_Rb_tree_node<std::unique_ptr<int> >]’
/usr/include/c++/4.8.2/bits/alloc_traits.h:254:4:   required from ‘static typename std::enable_if<std::allocator_traits<_Alloc>::__construct_helper<_Tp, _Args>::value, void>::type std::allocator_traits<_Alloc>::_S_construct(_Alloc&, _Tp*, _Args&& ...) [with _Tp = std::_Rb_tree_node<std::unique_ptr<int> >; _Args = {const std::unique_ptr<int, std::default_delete<int> >&}; _Alloc = std::allocator<std::_Rb_tree_node<std::unique_ptr<int> > >; typename std::enable_if<std::allocator_traits<_Alloc>::__construct_helper<_Tp, _Args>::value, void>::type = void]’
/usr/include/c++/4.8.2/bits/alloc_traits.h:393:57:   required from ‘static decltype (_S_construct(__a, __p, (forward<_Args>)(std::allocator_traits::construct::__args)...)) std::allocator_traits<_Alloc>::construct(_Alloc&, _Tp*, _Args&& ...) [with _Tp = std::_Rb_tree_node<std::unique_ptr<int> >; _Args = {const std::unique_ptr<int, std::default_delete<int> >&}; _Alloc = std::allocator<std::_Rb_tree_node<std::unique_ptr<int> > >; decltype (_S_construct(__a, __p, (forward<_Args>)(std::allocator_traits::construct::__args)...)) = <type error>]’
/usr/include/c++/4.8.2/bits/stl_tree.h:408:36:   required from ‘std::_Rb_tree_node<_Val>* std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_create_node(_Args&& ...) [with _Args = {const std::unique_ptr<int, std::default_delete<int> >&}; _Key = std::unique_ptr<int>; _Val = std::unique_ptr<int>; _KeyOfValue = std::_Identity<std::unique_ptr<int> >; _Compare = std::less<std::unique_ptr<int> >; _Alloc = std::allocator<std::unique_ptr<int> >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Link_type = std::_Rb_tree_node<std::unique_ptr<int> >*]’
/usr/include/c++/4.8.2/bits/stl_tree.h:1023:66:   required from ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr, std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr, _Arg&&) [with _Arg = const std::unique_ptr<int>&; _Key = std::unique_ptr<int>; _Val = std::unique_ptr<int>; _KeyOfValue = std::_Identity<std::unique_ptr<int> >; _Compare = std::less<std::unique_ptr<int> >; _Alloc = std::allocator<std::unique_ptr<int> >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::unique_ptr<int> >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr = std::_Rb_tree_node_base*]’
/usr/include/c++/4.8.2/bits/stl_tree.h:1482:33:   required from ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique_(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator, _Arg&&) [with _Arg = const std::unique_ptr<int>&; _Key = std::unique_ptr<int>; _Val = std::unique_ptr<int>; _KeyOfValue = std::_Identity<std::unique_ptr<int> >; _Compare = std::less<std::unique_ptr<int> >; _Alloc = std::allocator<std::unique_ptr<int> >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::unique_ptr<int> >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator = std::_Rb_tree_const_iterator<std::unique_ptr<int> >]’
/usr/include/c++/4.8.2/bits/stl_tree.h:1722:37:   required from ‘void std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(_II, _II) [with _InputIterator = const std::unique_ptr<int>*; _Key = std::unique_ptr<int>; _Val = std::unique_ptr<int>; _KeyOfValue = std::_Identity<std::unique_ptr<int> >; _Compare = std::less<std::unique_ptr<int> >; _Alloc = std::allocator<std::unique_ptr<int> >]’
/usr/include/c++/4.8.2/bits/stl_set.h:518:4:   required from ‘void std::set<_Key, _Compare, _Alloc>::insert(_InputIterator, _InputIterator) [with _InputIterator = const std::unique_ptr<int>*; _Key = std::unique_ptr<int>; _Compare = std::less<std::unique_ptr<int> >; _Alloc = std::allocator<std::unique_ptr<int> >]’
/usr/include/c++/4.8.2/bits/stl_set.h:530:9:   required from ‘void std::set<_Key, _Compare, _Alloc>::insert(std::initializer_list<_Tp>) [with _Key = std::unique_ptr<int>; _Compare = std::less<std::unique_ptr<int> >; _Alloc = std::allocator<std::unique_ptr<int> >]’
test.cpp:9:49:   required from here
/usr/include/c++/4.8.2/bits/stl_tree.h:140:49: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]’
    _M_value_field(std::forward<_Args>(__args)...) { }
                                                 ^
In file included from /usr/include/c++/4.8.2/memory:81:0,
                 from test.cpp:1:
/usr/include/c++/4.8.2/bits/unique_ptr.h:273:7: error: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^

What do I need to do to make this work?

Is a zero initialized std::atomic

Given foo.cpp:

#include <atomic>

namespace {
    std::atomic<int*> gets_zero_init;
    std::atomic<int*> gets_nullptr{nullptr};
}

I'm confident that gets_zero_init is zero-initialized. I'm also confident that gets_nullptr will be initialized with nullptr, I'm also fairly confident that gets_nullptr doesn't get zero-initialized, because std::is_trivially_constructible<decltype(gets_nullptr), int*>::value is false (at least, it is on my compiler). I'm however a little unclear on whether gets_nullptr is fully initialized at constant init, static init, or dynamic init. Which is it?

Furthermore, lets say, for the sake of argument, that I'm interested in ensuring that I'm using zero-initialization, so I go with the gets_zero_init approach. The pointer embedded in gets_zero_init will hold the all-zeros bit-pattern due to zero-initialization.

Is it guaranteed that the all-zeros bit pattern is equivalent to nullptr? In other words, if I want the semantics of gets_nullptr, can I rely on the zero-initialization of gets_zero_init to provide that?

How to remove a double free or corruption error in C++?

I am getting this error when I am calling sum3=sum(h3);

int sum(list<int> &l);
int main(){
int n1,sum1=0;
int n2,sum2=0;
int n3,sum3=0;
cin >> n1 >> n2 >> n3;
list<int> h1(n1);
for(int h1_i = 0;h1_i < n1;h1_i++){
   int num;
   cin >> num;
   h1.push_back(num);
}
list<int> h2(n2);
for(int h2_i = 0;h2_i < n2;h2_i++){
   int num;
   cin >> num;
   h2.push_back(num);
}
list<int> h3(n3);
for(int h3_i = 0;h3_i < n3;h3_i++){
   int num;
   cin >> num;
   h3.push_back(num);
}

sum1=sum(h1);
sum2=sum(h2);
sum3=sum(h3);
do{
    if(sum1!=sum2&&sum2!=sum3)
    {
        h1.pop_front();
        h2.pop_front();
        h3.pop_front();
        sum1=0;sum2=0;sum3=0;
        sum1=sum(h1);
        sum2=sum(h2);
        //sum3=sum(h3);   //Error while adding this         
    }
    else if(sum1==sum2&&sum1!=sum3)
    {
        h3.pop_front();
        sum3=0;
        sum3=sum(h3);
    }
    else if(sum1==sum3&&sum2!=sum3)
    {
        h2.pop_front();
        sum2=0;
        sum2=sum(h2);
    }
     else if(sum2==sum3&&sum1!=sum3)
    {
        h1.pop_front();
        sum1=0;
        sum1=sum(h1);
    }
}while(sum1!=sum2&&sum2!=sum3);
cout<<sum1;
return 0;
}

int sum(list<int> &l)
{
int sum=0;
list<int>::iterator p;
for(p=l.begin();p!=l.end();p++){
    sum+=*p;
}
return sum;     
}

What can be the possible problem? I know that there is some memory allocation issue but I can't find it. Everything works fine if that very line is commented.

Can non-atomic-load be reordered after atomic-acquire-load?

As known in since C++11 there are 6 memory orders, and in documentation written about std::memory_order_acquire:

memory_order_acquire

A load operation with this memory order performs the acquire operation on the affected memory location: no memory accesses in the current thread can be reordered before this load. This ensures that all writes in other threads that release the same atomic variable are visible in the current thread.

1. Non-atomic-load can be reordered after atomic-acquire-load:

I.e. it does not guarantee that non-atomic-load can not be reordered after acquire-atomic-load.

static std::atomic<int> X;
static int L;
...

void thread_func() 
{
    int local1 = L;  // load(L)-load(X) - can be reordered with X ?

    int x_local = X.load(std::memory_order_acquire);  // load(X)

    int local2 = L;  // load(X)-load(L) - can't be reordered with X
}

Can load int local1 = L; be reordered after X.load(std::memory_order_acquire);?

2. We can think that non-atomic-load can not be reordered after atomic-acquire-load:

Some articles contained a picture showing the essence of acquire-release semantics. That is easy to understand, but can cause confusion.

enter image description here

enter image description here

For example, we may think that std::memory_order_acquire can't reorder any series of Load-Load operations, even non-atomic-load can't be reordered after atomic-acquire-load.

3. Non-atomic-load can be reordered after atomic-acquire-load:

Good thing that there is clarified: Acquire semantics prevent memory reordering of the read-acquire with any read or write operation which follows it in program order. http://ift.tt/NFOHvq

But also known, that: On strongly-ordered systems (x86, SPARC TSO, IBM mainframe), release-acquire ordering is automatic for the majority of operations.

And Herb Sutter on page 34 shows: http://ift.tt/1pG7ykq

enter image description here

4. I.e. again, we can think that non-atomic-load can not be reordered after atomic-acquire-load:

I.e. for x86:

  • release-acquire ordering is automatic for the majority of operations
  • Reads are not reordered with any reads. (any - i.e. regardless of older or not)

So can non-atomic-load be reordered after atomic-acquire-load in C++11?

Determining Big O: Find 4 different numbers in array summing up to S

Given an array of numbers arr and a number S, find 4 different numbers in arr that sum up to S.

Write a function that gets arr and S and returns an array with 4 indices of such numbers in arr.

The solution I came up with involves recursively building up combinations of indices while making sure no combinations are counted more than once. I also prune the search tree by making sure the size of the solution set is no more than 4.

#include <iostream>
#include <vector>
using namespace std;

bool find_sol(vector<int> &N, vector<int> &I, int S, int sum){
  if (I.size() == 4)
    if (S == sum)
      return true;
    else
      return false;
  for (int i = 0; i < N.size(); ++i){
    if (I.empty() || I[I.size()-1] < i){
      I.push_back(i);
      if (find_sol(N,I,S,sum+N[i]))
        return true;
      else {
        I.pop_back();
      }
    }
  }
  return false;
}

int main(){
  int S = 23;
  vector<int> numbers = {1,3,5,6,7,8,9};
  vector<int> indices;
  find_sol(numbers,indices,S,0);

  // prints 0, 2, 5, 6
  for (int i = 0; i < indices.size(); ++i)
    cout << indices[i] <<" ";
  cout<<endl;

  return 0;
}

How can I determine the run time of this algorithm? I feel like it is something like O(n choose 4) but am not sure. The solution tells me the optimal run time is O(n^2).

Is it possible to have a std::vector of struct with a fexible array member?

I have a struct with a flexible array member that I need to use.

struct Record
{
     uint32_t length;
     Data contents[];
};

I'm able to initialize this and use it by doing something like this: (it would also work with malloc or any other dynamic allocation)

vector<Data> members;
vector<uint8_t> buffer;
Record myRecord;
buffer.resize(sizeof(Record) + members.size() * sizeof(Data));
myRecord = *(reinterpret_cast<Record*>(buffer.data());
myRecord.length = static_cast<uint32_t>(members.size());
// copy members to myRecord.contents

That works just fine. But now I need to have an interface that operates on batches of Record, and I have been trying to use an std::vector for this. Then problems start appearing, and I'm guessing it's because std::vector arranges all elements contiguously on memory, and since sizeof(Record) won't take into account the size of the contents (each vector element will hold only 4 bytes, instead of 4 bytes + size_of_contents * sizeof(Data)), the vector elements are actually sharing memory and then each element starts overwriting the contents of the previous element. Does that make sense?

If this really is the problem, I was wondering if there's any way to "force" the vector to allocate a specific size for each element (instead of whatever sizeof returns for the element's type). That way I could make sure that each vector element would have enough size. If that's not possible, is there an alternative solution? Maybe a different container that would allow me to do so? Please keep in mind that I do need to use the struct as it's defined (I would love to just replace the whole thing for a vector but unfortunately that's not possible)

universal and uniform initialization: `double` to `int`

Visual Studio 2015 Update 3. C++11\C++14.

For int:

constexpr int ci1 {50};
constexpr int ci2 {500};

char c1 {ci1}; // OK
char c2 {ci2}; // compilation error

I.e. the universal and uniform initialization can check the value in the compilation mode (from int to char). This case was mentioned by Bjarne Stroustrup in his book.

I expected that this is true for case double to int,but it doesn't work for Visual Studio 2015 Update 3:

constexpr double cd {4.0};
int i1 {cd}; // compilation error

Is it correct behaviour (for my second code example) or maybe it is specific for Visual Studio?

C++/OpenGL: How does Tesselation work?

I've got the book "OpenGL SuperBible Seventh Edition" and I'm now wondering how the tesselation works? I'm currently in chapter 3 of the book and I do not really understand the explanation of the tesselation with the tesselation control shaders, the tesselation engine and the tesselation evaluataion shaders.

So I'm using

  • OpenGL 4.5
  • C++11
  • Windows

So can anyone explain to me in detail how tesselation works in OpenGL 4.5 and what control points, batches etc. are?

Thx in advance. ShadowDragon

static constexpr member storage

If I write a trait like this,

template <typename T>
struct is_int {
  static constexpr bool value = false;
};

template <>
struct is_int<int> {
  static constexpr bool value = true;
};

Is the value actually stored in memory when the program runs? For example, if I use this trait on a million different types, does the program use 1 MB of memory to store these values?

To paraphrase, is there still any advantage to using

template <typename T>
struct is_int {
  enum { value = 0; }
};

template <>
struct is_int<int> {
  enum { value = 1; }
};

Why I can't increment the parameter of the simple constexpr function?

Visual Studio 2015 Update 3.

I read the Programming. Principles and Practice Using C++ (second edition) by Bjarne Stroustrup. I learn the constexpr functions...

It works:

constexpr int get_value(int n) {
    return n + 1;
}

But I can't compile this (instead of the first variant):

constexpr int get_value(int n) {
    return ++n;
}

I get the error:

constexpr function return is non-constant

The n is the local variable for the get_value function. I.e. n variable changing doesn't influence to external code.

Why the second variant of the get_value function is wrong?

Mathematically same condition statements, different results

I was trying to solve a coding problem that can be found here.

I tried these two definitions for my For loop

for(i=0;i+(num*len)-1<A.size();i++)

and

for(i=0;i<A.size()-(num*len)+1;i++)

Later in the code, I'm using the string.substr function to obtain substrings. For some reason, the 1st form works fine, but the second one throws the following error.

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr
Aborted

Can someone explain to me why this is happening? I'm using C++11 with GCC 4.8.

Can I assign/move a new value into a unique_ptr inside a tuple?

The need to do this has arisen since I want MyClass::run to use all the other tuple elements. Basically, I have a vector of these tuples to form a kind of table. I couldn't figure out myself how to properly do this. Can you help?

using namespace std;
tuple<unique_ptr<thread>, MyOtherInfo> tup = forward_as_tuple(nullptr, MyOtherInfo());
get<0>(tup) = make_unique<thread>(&MyClass::run, this, &tup);

Making std::to_string work with void pointers (and do we really want to)

I have some code which std::to_string()'s a variable whose type is a template parameter. Now, sometimes this parameter needs to be a void. No problem, right? I should just get the same thing as I would when I std::cout << my_ptr, right? ... Unfortunately not, this doesn't happen.

  • Is it "legitimate" for me to want this to work?
  • Is there anything better than overloading std::to_string for void*'s and using an std::stringstream for the operator<< ?

Set Cookie from response in WinHttp

I've a code that makes a post request to a server but I'm trying to set a Cookie from the response. (Just in case, I'm doing a request to a BurningBoard Login)

Here you have my code:

HttpsWebRequestPost("example.com", "/api.php?action=UserLogin", "loginUsername=" + USERNAME + "&loginPassword=" + PASSWORD + "&url=/index.php?page=Portal");

And:

#pragma once

#include <Windows.h>
#include <WinHttp.h>
#include <stdio.h>
#include <iostream> //getchar
#include <fstream>

#pragma comment(lib, "winhttp.lib")

using namespace std;

std::wstring get_utf16(const std::string &str, int codepage)
{
    if (str.empty()) return std::wstring();
    int sz = MultiByteToWideChar(codepage, 0, &str[0], (int)str.size(), 0, 0);
    std::wstring res(sz, 0);
    MultiByteToWideChar(codepage, 0, &str[0], (int)str.size(), &res[0], sz);
    return res;
}

string HttpsWebRequestPost(string domain, string url, string dat)
{
    //Extra
    LPSTR  data = const_cast<char *>(dat.c_str());;
    DWORD data_len = strlen(data);


    wstring sdomain = get_utf16(domain, CP_UTF8);
    wstring surl = get_utf16(url, CP_UTF8);
    string response;

    DWORD dwSize = 0;
    DWORD dwDownloaded = 0;
    LPSTR pszOutBuffer;
    BOOL  bResults = FALSE;
    HINTERNET  hSession = NULL,
        hConnect = NULL,
        hRequest = NULL;

    // Use WinHttpOpen to obtain a session handle.
    hSession = WinHttpOpen(L"WinHTTP Example/1.0",
        WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
        WINHTTP_NO_PROXY_NAME,
        WINHTTP_NO_PROXY_BYPASS, 0);

    // Specify an HTTP server.
    if (hSession)
        hConnect = WinHttpConnect(hSession, sdomain.c_str(),
            INTERNET_DEFAULT_HTTP_PORT, 0);

    // Create an HTTP request handle.
    if (hConnect)
        hRequest = WinHttpOpenRequest(hConnect, L"POST", surl.c_str(),
            NULL, WINHTTP_NO_REFERER,
            WINHTTP_DEFAULT_ACCEPT_TYPES,
            0);

    LPCWSTR additionalHeaders = L"Content-Type: application/x-www-form-urlencoded\r\n";
    DWORD headersLength = -1;

    // Send a request.
    if (hRequest)
        bResults = WinHttpSendRequest(hRequest,
            additionalHeaders, headersLength,
            (LPVOID)data, data_len,
            data_len, 0);


    // End the request.
    if (bResults)
        bResults = WinHttpReceiveResponse(hRequest, NULL);

    // Keep checking for data until there is nothing left.
    if (bResults)
    {
        do
        {
            // Check for available data.
            dwSize = 0;
            if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
                printf("Error %u in WinHttpQueryDataAvailable.\n",
                    GetLastError());

            // Allocate space for the buffer.
            pszOutBuffer = new char[dwSize + 1];
            if (!pszOutBuffer)
            {
                printf("Out of memory\n");
                dwSize = 0;
            }
            else
            {
                // Read the data.
                ZeroMemory(pszOutBuffer, dwSize + 1);

                if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer,
                    dwSize, &dwDownloaded))
                    printf("Error %u in WinHttpReadData.\n", GetLastError());
                else
                    //printf("%s", pszOutBuffer);
                    response = response + string(pszOutBuffer);
                // Free the memory allocated to the buffer.
                delete[] pszOutBuffer;
            }
        } while (dwSize > 0);
    }

    // Report any errors.
    if (!bResults)
        printf("Error %d has occurred.\n", GetLastError());

    // Close any open handles.
    if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    if (hSession) WinHttpCloseHandle(hSession);

    return response;

}

Finally, this is what I get as response in WireShark:

Hypertext Transfer Protocol
    HTTP/1.1 200 OK\r\n
    Request Version: HTTP/1.1
    Status Code: 200
    Response Phrase: OK
    Date: Sat, 30 Jul 2016 11:55:02 GMT\r\n
    Server: Apache\r\n
    Set-Cookie: wcf_cookieHash=*******hash******; HttpOnly\r\n
    Set-Cookie: wcf_boardLastActivityTime=1469879702; expires=Sun, 30-Jul-2017 11:55:02 GMT; HttpOnly\r\n
    Cache-Control: max-age=0, private\r\n
    Expires: Sat, 30 Jul 2016 11:55:02 GMT\r\n
    Vary: Accept-Encoding\r\n
    Connection: close\r\n
    Transfer-Encoding: chunked\r\n
    Content-Type: text/html; charset=UTF-8\r\n
    \r\n

Can somebody help me to add cookies please? Thanks

Is there any effect on the operations with the variables independent of consume atomic-load?

As known, there are 6 std::memory_order's, and 2 of its:

  • acquire-semantic used for loads - avoids reordering Load-Load and Load-Store
  • release-semantic used for stores - avoids reordering Store-Store and Load-Store

enter image description here

I.e. for acquire-semantic, only S = local1; can be executed after X.load(std::memory_order_acquire);:

static std::atomic<int> X;
static int L, S;
...

void thread_func() 
{
    int local1 = L;  // load(L)-load(X) - can't be reordered with X
    S = local1;      // store(S)-load(X) - !!! can be reordered with X !!!

    int x_local = X.load(std::memory_order_acquire);  // load(X)

    int local2 = L;  // load(X)-load(L) - can't be reordered with X
    S = local2;      // load(X)-store(S) - can't be reordered with X
}

But which of reorders across load(X) can be for consume-semantic?

static std::atomic<int> *X;
static int L1, L2, S1, S2;
static int L, S;
...

void thread_func() 
{
    int *x_ptr_local = new int(1);


    int local1 = L1;  // load(L1)-load(X) - !!! can be reordered with X !!!
    S1 = local1;      // store(S1)-load(X) - !!! can be reordered with X !!!

    int dependent_x1 = *x_ptr_local;  // load(x_ptr)-load(X) - can't be reordered with X
    S = dependent_x1;                 // store(S)-load(X) - can't be reordered with X

    x_ptr_local = X.load(std::memory_order_consume);  // load(X)

    int dependent_x2 = *x_ptr_local;  // load(X)-load(x_ptr) - can't be reordered with X
    S = dependent_x2;                 // load(X)-store(S) - can't be reordered with X

    int local2 = L2;  // load(X)-load(L2) - !!! can be reordered with X !!!
    S2 = local2;      // load(X)-store(S2) - !!! can be reordered with X !!!
}

Is it true, that only operations with dependent_x1 and dependent_x2 can't be reordered across X.load(std::memory_order_consume)?

And all of operations with variables L1, L2, S1, S2 can be reordered across X.load(std::memory_order_consume) - i.e. can be performed either before or after X.load(std::memory_order_consume), isn't it?

POST Request in WinHttp c++

I'm trying to make a POST request in c++ with the WinHTTP api Click to the Microsoft Guide, the problem is that the example that is available in the microsoft webpage is a "GET" request so I came up with this code searching on the internet:

First we call the code:

HttpsWebRequestPost("example.com", "/api.php?action=UserLogin", "loginUsername=" + USERNAME + "&loginPassword=" + PASSWORD + "&url=/index.php?page=Portal");

Then:

#include <Windows.h>
#include <WinHttp.h>
#include <stdio.h>
#include <iostream> //getchar
#include <fstream>

#pragma comment(lib, "winhttp.lib")

using namespace std;

std::wstring get_utf16(const std::string &str, int codepage)
{
    if (str.empty()) return std::wstring();
    int sz = MultiByteToWideChar(codepage, 0, &str[0], (int)str.size(), 0, 0);
    std::wstring res(sz, 0);
    MultiByteToWideChar(codepage, 0, &str[0], (int)str.size(), &res[0], sz);
    return res;
}

string HttpsWebRequestPost(string domain, string url, string dat)
{
    //Extra
    LPSTR  data = const_cast<char *>(dat.c_str());;
    DWORD data_len = strlen(data);


    wstring sdomain = get_utf16(domain, CP_UTF8);
    wstring surl = get_utf16(url, CP_UTF8);
    string response;

    DWORD dwSize = 0;
    DWORD dwDownloaded = 0;
    LPSTR pszOutBuffer;
    BOOL  bResults = FALSE;
    HINTERNET  hSession = NULL,
        hConnect = NULL,
        hRequest = NULL;

    // Use WinHttpOpen to obtain a session handle.
    hSession = WinHttpOpen(L"WinHTTP Example/1.0",
        WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
        WINHTTP_NO_PROXY_NAME,
        WINHTTP_NO_PROXY_BYPASS, 0);

    // Specify an HTTP server.
    if (hSession)
        hConnect = WinHttpConnect(hSession, sdomain.c_str(),
            INTERNET_DEFAULT_HTTP_PORT, 0);

    // Create an HTTP request handle.
    if (hConnect)
        hRequest = WinHttpOpenRequest(hConnect, L"POST", surl.c_str(),
            NULL, WINHTTP_NO_REFERER,
            WINHTTP_DEFAULT_ACCEPT_TYPES,
            0);

    // Send a request.
    if (hRequest)
        bResults = WinHttpSendRequest(hRequest,
            WINHTTP_NO_ADDITIONAL_HEADERS, 0,
            (LPVOID)data, data_len,
            data_len, 0);


    // End the request.
    if (bResults)
        bResults = WinHttpReceiveResponse(hRequest, NULL);

    // Keep checking for data until there is nothing left.
    if (bResults)
    {
        do
        {
            // Check for available data.
            dwSize = 0;
            if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
                printf("Error %u in WinHttpQueryDataAvailable.\n",
                    GetLastError());

            // Allocate space for the buffer.
            pszOutBuffer = new char[dwSize + 1];
            if (!pszOutBuffer)
            {
                printf("Out of memory\n");
                dwSize = 0;
            }
            else
            {
                // Read the data.
                ZeroMemory(pszOutBuffer, dwSize + 1);

                if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer,
                    dwSize, &dwDownloaded))
                    printf("Error %u in WinHttpReadData.\n", GetLastError());
                else
                    //printf("%s", pszOutBuffer);
                    response = response + string(pszOutBuffer);
                // Free the memory allocated to the buffer.
                delete[] pszOutBuffer;
            }
        } while (dwSize > 0);
    }

    // Report any errors.
    if (!bResults)
        printf("Error %d has occurred.\n", GetLastError());

    // Close any open handles.
    if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    if (hSession) WinHttpCloseHandle(hSession);

    return response;

}

But using WireShark I only get:

Hypertext Transfer Protocol
    POST ***************** HTTP/1.1\r\n
    Connection: Keep-Alive\r\n
    User-Agent: WinHTTP Example/1.0\r\n
    Content-Length: **\r\n
    Host: ******\r\n
    \r\n

Anyone can help meto fix this or know an easier method? Thanks

How to modify an atomic variable

I have two atomic variables and two threads plus the main thread. One thread continuously receives data from UDP port and stores data into std::atomic<double> m_udpData. The second thread gets m_udpData and stores the data into std::atomic<double> m_delayedData. In the main thread, I need to retrieve m_delayedData. The two threads and atomic variables belong to one class Slave. It seems that I can't assign a value to an atomic variable. Is there a workaround for this problem in a safe manner?

// First thread
void Slave::updateUDPData()
{
    while (true){
        server->recieve(m_udpData);
    }
}

// Second thread
void Slave::updateData()
{
    while (true){
        std::this_thread::sleep_for(m_delay);
        m_delayedData = m_udpData; // <- yields an error. 
    }
}

operator = does not work with fstream

I am having a structure

struct myStruct {
    fstream fp;
    char *buffer;
    size_t size;
};

I am new to C++ and trying to write a code wherein one thread will read from a file into buffer and main thread will write the buffer to other file. The sample of the code is as follows:

int main() {
    pthread tid1;
    struct myStruct readArgs;
    fstream fileP, fileP2;
    fileP.open("/tmp/20MBFile", fstream::in);
    fileP2.open("/tmp/trial-file", fstream::out);
    char *buffer;
    readArgs.fp = fileP;
    readArgs.buffer = buffer;
    readArgs.size = 1048576;
    pthread_create(&tid1, NULL, Read, &readArgs);
    pthread_join(tid1, NULL);
    fileP2.write(buffer, 1048576);
    ......
}

The read function is as follows:

void *Read(struct myStruct *readArgs) {
    readArgs->fp.read(readArgs->buffer, readArgs->size);
    pthread_exit(NULL);
}

however, when I compile my code I get following errors:

error: use of deleted function 'std::basic_fstream& std::basic_fstream::operator=(const std::basic_fstream&)' readArgs.fp = fileP;

AND

error: invalid conversion from 'void* ()(myStruct)' to 'void* ()(void)' [-fpermissive] pthread_create(&tid1, NULL, Read, &readArgs); ^ In file included from /usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../../../include/c++/4.8.3/x86_64-redhat-linux/bits/gthr-default.h:35:0, from /usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../../../include/c++/4.8.3/x86_64-redhat-linux/bits/gthr.h:148, from /usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../../../include/c++/4.8.3/ext/atomicity.h:35, from /usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../../../include/c++/4.8.3/bits/ios_base.h:39, from /usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../../../include/c++/4.8.3/ios:42, from /usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../../../include/c++/4.8.3/ostream:38, from /usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../../../include/c++/4.8.3/iostream:39, from projects/sshsm/experiments/common/bufferpool.h:1, from projects/sshsm/experiments/common/bufferpool.cc:2: /usr/include/pthread.h:232:12: error: initializing argument 3 of 'int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)' [-fpermissive] extern int pthread_create (pthread_t *__restrict __newthread,

Am I missing anything here? Thanks in advance!

std::sort - indirection requires pointer operand

I want to sort a vector of Sprite objects

std::function<bool(const Sprite&,const Sprite&)> fn;
fn = [](auto&& a, auto&& b) ->bool { return a.pos.x > b.pos.x; };
std::sort(sprites.begin(), sprites.end(), fn);

/usr/bin/../lib/gcc/x86_64-redhat-linux/5.3.1/../../../../include/c++/5.3.1/bits/predefined_ops.h:123:31: fatal error: indirection requires pointer operand ('Sprite' invalid) { return bool(_M_comp(*__it1, *__it2)); }

But if I inline the sorting function there is no error. What is the problem?

Obtain correct UTM/GMT time regardless of users clock correctness

I recently discovered that attempting to get UTM/GMT time can fail (not return the correct time &/or date) if the user has not set their system time correctly.

Is there a way to always obtain the correct time in UTM/GMT using C11, C++11 or C++14 (or even better using a WinAPI function)? If not maybe my application can get this from a HTTP request to some server and read the HTTP response headers?

vendredi 29 juillet 2016

type does not provide a call operator

I have this function, order, which returns vector<Node*>

vector<Node*> order(vector<string> nodes, vector<pair<string, string>> dependencies) {
             Graph graph = buildGraph(nodes, dependencies);
             vector<Node*> order = buildOrder(graph.getNodes());
             return order;
}

and I call it like this:

vector<Node*> order2 = order(nodes, deps);

However, the compiler gives this error:

error: type 'std::__1::vector<Node *, std::__1::allocator<Node *> >' does not provide a call operator
        vector<Node*> order2 = order(nodes, deps);
                               ^~~~~
1 error generated.

What is going wrong? 'std::__1::vector<Node *, std::__1::allocator<Node *> >' seems to suggest that there is a vector<Node*, <Node*>> or something going on, but I can't seem to figure this out.

custom type requires an initializer to declare with auto?

I have this type:

  9 class Node {
 10         string name;
 11         int    dependencies;
 12         vector<Node*> children;
 13         unordered_map<string, Node*> map;
 14
 15
 16         public:
 17                 Node(string name) : name(name) {}
 18                 void decrementDependency() { dependencies--;}
 19                 void incrementDependency() { dependencies++;}
 20                 string getName() { return name; }
 21                 vector<Node*> getChildren() { return children; }
 22                 int getNumDependencies() { return dependencies; }
 23
 24                 void addDependent(Node* node) {
 25                         map[node->getName()] = node;
 26                         children.push_back(node);
 27                         node->incrementDependency();
 28                 }
 29 };

and I am trying to iterate through a vector<Node*> in a range-based loop, like so:

 for (auto Node* node : children) {
      node->decrementDependency();
 }

However, the compiler gives this error, error: declaration of variable 'Node' with type 'auto' requires an initializer.

Why does this happen? Is it because it's a vector of pointers to Nodes?

Lexicographic Order in Multidimensional Array C++

I'm having trouble with one final task that my program should do. Having my output character in a lexicographic order.

For example, if I input bbbaaa it should have an output of

Frequencies: a 3 b 3

Not

Frequencies: b 3 a 3

Can anyone help me solve this problem? Here is my code:

#include <iostream>
#include <string>
#include <stdio.h>
#include <ctype.h>

using namespace std;

void sort(char letters[], int integers[], int size);
void swap_letters(char& first, char& second, int& int1, int& int2);
int index_of_largest(const int integers[], int start_index, int number_used);

int main(){
  const int MAX_CHARS = 200;
  char letters[MAX_CHARS] = {'\0'};
  int integers[MAX_CHARS] = {'\0'};
  int index, size = 0;
  char character;

  cout << "Enter text:" << endl;
  cin.get(character);
  character = tolower(character);
  while (character!= '.' && size < MAX_CHARS){
    if(isalpha(character)){
      index = 0;
      while (index < size){
        if(letters[index] == character)
          break;
        else
          index++;
      }
      if (index < size){
        integers[index] = integers[index] + 1;
      }
      else{
        letters[index] = character;
        integers[index] = 1;
        size++;
      }
    }
    cin.get(character);
    character = tolower(character);
  }
  letters[index] = tolower(letters[index]);
  sort(letters, integers, size);

  cout << "Frequencies:"<< endl;

  for(int i = 0; i < size; i++){
    cout << letters[i]  << " " << integers[i] << endl;
  }
  return 0;
}

void sort(char letters[], int integers[], int size){
    for (int i = 0; i < size -1; i++){
      int j = index_of_largest(integers, i, size);
      swap_letters(letters[i], letters[j], integers[i], integers[j]);
  }
}
void swap_letters(char& first, char& second, int& int1, int& int2){
  char temp_char = first;
  first = second;
  second = temp_char;
  int temp_int = int1;
  int1 = int2;
  int2 = temp_int;
}
int index_of_largest(const int integers[], int start_index, int number_used){
  int max_int = integers[start_index];
  int max_int_index = start_index;
  for (int index = start_index + 1; index < number_used; index++){
    if (integers[index] > max_int){
      max_int = integers[index];
      max_int_index = index;
    }
  }
  return max_int_index;
}

failbit set when creating a file, when the file name is passed using composition syntax

I have the following function which creates files as expected when run on its own:

MatchedFilter::MatchedFilter(double * dataIn, int dataInSize, std::string name)
{
    fileNameOutput = name;

    fileNameOutput.insert((name.length() - 4),"OUTPUT");

    std::ofstream dataDump(fileNameOutput);

    std::ios_base::iostate errcheck = dataDump.rdstate();

    if((errcheck & std::fstream::failbit) != 0)
    {
      std::cout << "Failbit has occured" << std::endl;
    }else if((errcheck & std::fstream::badbit) != 0)
    {
      std::cout << "Badbit has occured" << std::endl;
    }else if((errcheck & std::fstream::eofbit) != 0)
    {
      std::cout << "EndofFile bit has occured" << std::endl;
    }  
}  

However when I create a MatchedFilter object inside a second class called DeModulator using composition, and pass a const string for the name variable the file fails to create, and I get a Failbit.

Here is the DeModulator class:

DeModulator::DeModulator(double * dataIn, int dataInSize) : 
filter2k(dataIn,dataInSize,"data/FilterKernal/2k.txt"), 
filter1k(dataIn,dataInSize,"data/FilterKernal/1k.txt")
{

}

What is wrong with passing a string const using this method, to create open a file?

Ubuntu G++ C++11

C++11: reinterpreting array of structs as array of struct's member

Consider the following type:

struct S
{
    char v;
};

Given an array of const S, is it possible to, in a standard conformant way, reinterpret it as an array of const char whose elements correspond to the value of the member v for each of the original array's elements, and vice-versa? For example:

const S a1[] = { {'a'}, {'4'}, {'2'}, {'\0'} };
const char* a2 = reinterpret_cast< const char* >(a1);

for (int i = 0; i < 4; ++i)
    std::cout << std::boolalpha << (a1[i].v == a2[i]) << ' ';

Is the code above portable and would it print true true true true? If not, is there any other way of achieving this?

Obviously, it is possible to create a new array and initialize it with the member v of each element of the original array, but the whole idea is to avoid creating a new array.

C++ code with poco json crashes after method ends

I have this very simple C++ method that uses poco json for querying a json string. Apparently it crashes after the method ends. The details of the crash are after my source code

void SomeClass::processJson(std::shared_ptr<Foo> code,std::string& json)
{
    try
    {
        std::string json_str = json;
        Parser parser;
        Var result;

        ParseHandler handler;
        parser.setHandler(&handler);
        parser.parse(json_str);
        result = handler.asVar();

        Query query(result);
        Poco::JSON::Array::Ptr arr= query.findArray("result.payload.infos");

        int t = arr->size();

    } catch (...)
    {

    }
}

Now as soon as the method ends i get a crash indicating this code in the stack trace in Var.h of POCO

#ifdef POCO_NO_SOO

    VarHolder* content() const
    {
        return _pHolder;
    }

    void destruct()
    {
        if (!isEmpty()) delete content();
    }

    VarHolder* _pHolder;

#else

A copy of the stack trace after this method is below

enter image description here

HashTable Implementation Get and Set Operator Overloading

I'm trying to implement a basic hashtable. I'm using a LinkedList to resolve collisions.

My get and set methods are giving me a bunch of trouble, and I'm not really sure what the issue is. I believe I'm overloading the operator's correctly, and I think my LinkedList append functionality is broken.

class HashTable {
  struct Node{
    int key;
    int value;
    Node *next;
  };
  Node **table;
  int hash_func(int key) const {
    return key % TABLE_SIZE;
  }
public:
  HashTable() {
    table = new Node*[TABLE_SIZE]();
    for (int i = 0; i < TABLE_SIZE; ++i)
      table[i] = nullptr;
  }

  int& operator[](int const key) {
    int h_key = hash_func(key);

    while(table[h_key]) {
      table[h_key] = table[h_key]->next;
    }

    table[h_key] = new Node;
    table[h_key]->key = key;
    table[h_key]->next = table[h_key];

    return table[h_key]->value;
  }

  int operator[](int const key) const {
    int h_key = hash_func(key);

    while (table[h_key]) {
      if (table[h_key]->key == key) {
        return table[h_key]->value;
      }
      table[h_key] = table[h_key]->next;
    }
    return 0;
  }
};

Issues with map (2)

when I try to build below code with VS2010 it end in error

#include <windows.h>
#include <map>

using namespace std;


struct WayStruct{
    double ID;
    string Neighbours;
};
map <char, WayStruct> WayMap;
WayStruct WaysFind;


int main(int argc, char *argv[])
{     
                    WaysFind.ID=9999;
                    WaysFind.Neighbours="test";
                    WayMap.insert(make_pair("123",WaysFind));


}

VS2010 is returning below error(s)

c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\utility(163): error C2440: 'initializing' : cannot convert from 'const char *' to 'const char'
              There is no context in which this conversion is possible
              c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\utility(255) : see reference to function template instantiation 'std::_Pair_base<_Ty1,_Ty2>::_Pair_base<_Ty,WayStruct>(_Other1 &&,_Other2 &&)' being compiled
              with
              [
                  _Ty1=const char,
                  _Ty2=WayStruct,
                  _Ty=const char *,
                  _Other1=const char *,
                  _Other2=WayStruct
              ]
              c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xmemory(208) : see reference to function template instantiation 'std::pair<_Ty1,_Ty2>::pair<const char*,WayStruct>(std::pair<const char *,_Ty2> &&)' being compiled
              with
              [
                  _Ty1=const char,
                  _Ty2=WayStruct
              ]
              c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xmemory(280) : see reference to function template instantiation 'void std::allocator<_Ty>::construct<std::pair<_Ty1,_Ty2>>(std::pair<const
_Kty,_Ty2> ,_Other &&)' being compiled
              with
              [
                  _Ty=std::pair<const char,WayStruct>,
                  _Ty1=const char *,
                  _Ty2=WayStruct,
                  _Kty=char,
                  _Other=std::pair<const char *,WayStruct>
              ]
              c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xtree(592) : see reference to function template instantiation 'void std::_Cons_val<std::allocator<_Ty>,_Ty,std::pair<_Ty1,_Ty2>>(_Alloc &,std::pair<const _Kty,_Ty2> *,std::pair<_Ty1,_Ty2> &&)' being compiled
              with
              [
                  _Ty=std::pair<const char,WayStruct>,
                  _Ty1=const char *,
                  _Ty2=WayStruct,
                  _Alloc=std::allocator<std::pair<const char,WayStruct>>,
                  _Kty=char
              ]
              c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xtree(755) : see reference to function template instantiation 'std::_Tree_nod<_Traits>::_Node
*std::_Tree_val<_Traits>::_Buynode<_Ty>(_Valty &&)' being compiled
              with
              [
                  _Traits=std::_Tmap_traits<char,WayStruct,std::less<char>,std::allocator<std::pair<const char,WayStruct>>,false>,
                  _Ty=std::pair<const char *,WayStruct>,
                  _Valty=std::pair<const char *,WayStruct>
              ]
              Source.cpp(19) : see reference to function template instantiation 'std::pair<_Ty1,_Ty2> std::_Tree<_Traits>::insert<std::pair<const char *,WayStruct>>(_Valty &&)' being compiled
              with
              [
                  _Ty1=std::_Tree_iterator<std::_Tree_val<std::_Tmap_traits<char,WayStruct,std::less<char>,std::allocator<std::pair<const char,WayStruct>>,false>>>,
                  _Ty2=bool,
                  _Traits=std::_Tmap_traits<char,WayStruct,std::less<char>,std::allocator<std::pair<const char,WayStruct>>,false>,
                  _Valty=std::pair<const char *,WayStruct>
              ]
    c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\utility(163): error C2439: 'std::_Pair_base<_Ty1,_Ty2>::first' : member could not be initialized
              with
              [
                  _Ty1=const char,
                  _Ty2=WayStruct
              ]
              c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\utility(166) : see declaration of 'std::_Pair_base<_Ty1,_Ty2>::first'
              with
              [
                  _Ty1=const char,
                  _Ty2=WayStruct
              ]

    Build FAILED.

Prevent std::function in gcc from allocating memory or increase threshhold

Is there any way to prevent std::function in gcc from dynamically allocating memory for larger function objects?

I would have expected the following code to work without dynamic allocation:

#include <functional>
#include <iostream>

// replace operator new and delete to log allocations
void* operator new (std::size_t n) {
    std::cout << "Allocating " << n << " bytes" << std::endl;
    return malloc(n);
}
void operator delete(void* p) throw() {
    free(p);
}

  class TestPlate
  {
    private:
        int value;

    public:
        int getValue(){ return value; }
        void setValue(int newValue) { value = newValue; }

        int doStuff(const std::function<int()>& stuff) { return stuff(); }

  };

int main()
{
    TestPlate testor;
    testor.setValue(15);
    const std::function<int()>& func =  std::bind(&TestPlate::getValue, &testor);

    std::cout << testor.doStuff(func) << std::endl;
    testor.setValue(25);
    std::cout << testor.doStuff(func) << std::endl;
}

However it allocates 24 bytes. As far as I am able to tell this is because the pointer to method requires 16 bytes and the pointer to the class instance another 8 bytes. This seems to be either A larger than the internal memory available to the function object or B a plain bug.

I was wondering whethere there are is any way to circumvent this type of behavior without changing the signature of the std::function or creating a lot of additional wrapper code.

C++11: Default constructor: Implicit or Excplicit?

When am I supposed to use the default keyword in C++11?

Is it now considered bad to write

struct Foo {

};

and one should write

struct Foo {

  Foo() = default;


};

?

C++11 way of initializing value type member variable

What is the correct way of instantiating Bar with its default constructor?

1)

struct Foo {
  Bar bar;
};

2)

struct Foo {
  Bar bar{};
};

3)

struct Foo {
  Bar bar;

  Foo : bar(Bar()) {}
};

4)

?

Multithreading with C++11

I have a list of jobs, let say N=400 on a 12 core machine. Each of these job took in average a 0.5 second's. The question is: "What is the fastest way to calculate all jobs?"

I've done this with a std::vector of task's, a mutex and 12 runnings threads, each fetching a new job after finish the old one + remove job from vector (with pthread or std::thread).

Now i want to use C++11 and im a little bit confused. std::future, std::packaged_task and std::thread ?

Array related not able to find the correct ans

given an array a of size n consisting of non-negative integers. You have to find length of longest subarray of this array such that sum of subarray is even.

Wrapping std::map and provide pointer to element

I am using a library which offers a function foo(Widget*).

My Widgets are stored in

struct WidgetManager {

  std::map<int, Widget> dict;

  ??? getWidget(int id);

}

Originally I stored (raw) Widget pointers in the std::map just because it was convenient to pass them to foo. If I wan't to store the actual Widgets in the map, what should the return type of getWidget be so that I can pass a pointer of the Widget to foo?

I am compelled to make it of type iterator, but I don't like that I have to access itr->second to get the Widget(pointer).

undefined reference to `XkbGetIndicatorState'

I am trying to compile following code in CLION it isn't giving me any errors in the ide.

void EntityListService::aimbot() 
{
   Display* d = XOpenDisplay((char*)0);

   if (d) 
   {
       unsigned n;

       XkbGetIndicatorState(d, XkbUseCoreKbd, &n);

       printf((n & 1)?"caps on\n":"caps off\n");
  }

   std::cout << entityList[1]->getHealth() << std::endl;
   usleep(1);
}

However when I try to run the code I get the following errors

EntityListService.cpp:25: undefined reference to `XOpenDisplay'

EntityListService.cpp:30: undefined reference to XkbGetIndicatorState'

I think it has something to do with adding -lX11 as argument I tried everywhere in the CLION ide to add arguments but nothing works could somebody give a summary on how to add the -lX11 argument when I press the run key.

decltype of member function pointer as template argument in c++11

I am trying to write a wrapper function which links to a function pointer at compile time, thus I wrote the following code which works perfectly fine in C++11:

#include <iostream>

template<typename Fn, Fn func, typename... Args>
typename std::result_of<Fn(Args...)>::type callfunc(Args&&... args){
  //do something else here
  return (*func)(args...);
}

double add(double a, double b){
  return a+b;
}

int main(){
  std::cout << callfunc<decltype(&add), &add>(2.0, 3.0) << "\n";
}

However if I try to do the same thing with a member function like this

#include <iostream>

template<typename Fn, Fn func, typename... Args>
typename std::result_of<Fn(Args...)>::type callfunc(Args&&... args){
  //do something else here
  return (*func)(args...);
}
class testclass {
public:
  double testadd(double a, double b);
  void run();
};

double testclass::testadd(double a, double b){
  return a+b;
}

void testclass::run(){
  std::cout << 
  callfunc<decltype(&testclass::testadd), &testclass::testadd>(2.0, 3.0) 
  // ^^^^^ this won't compile! ^^^^
  << "\n"; 
}

int main(){
  testclass obj;
  obj.run()
}

I get the following compiler error:

error: indirection requires pointer operand ('double (testclass::*)(double,double)' invalid) return (*func)(args...);

What am I doing wrong?

Issues with map

I do have below struct defined

struct WayStruct{
    double ID;
    string Neighbours;
};

and below map

map <double,WayStruct> WayMap;

To add a new element to this map I use

WaysFind.ID=999;
WaysFind.Neighbours="test";
WayMap.insert(1234,WaysFind);

However I can not get this compiled. Dev-C++ end in error with

[Error] no matching function for call to 'std::map<double, WayStruct>::insert(double, WayStruct&)' 

Can someone tell what I'm doing wrong here?

stream several files continuously in C++

My question is similar to this, but I have not found any C++ references for this problem.

There is a list of big files to read and process. What is the best way to create an input stream that would get data from the files one by one, opening the next file automatically upon the end of the previous file? This stream will be given to a processing function which sequentially reads block of variable size, across the file boundaries.

How do I create a pair combinations of vector elements using c++?

How do I create a pair combinations of vector elements using c++ ,with no repeated elements ,for example :

A(1,2,3,4)

1,2

1,3

1,4

2,1

2,3

2,4

3,1

3,2

3,4

4,1

4,2

4,3

Wrapping a templated function call in a lambda

I am trying to write code to do something similar (code written for demonstration purposes) to this:

template <typename F, typename Args...>
inline auto runFunc(F func) -> foo
{
    return foo([func](Args... args) -> std::result_of<F>::type
        {
            // Do something before calling func
            func(args...);
            // Do something after call func
        });
}

So basically I am trying to write a function that returns an object that takes lambda that matches the templated function type. Obviously this code won't work because I do not have Args... defined. How would I solve this in C++11?

Replacing a type within a tuple in C++11

I'm trying to use templates in C++ to do the following:

I have a function like this:

template<typename... Args>
void f1(const std::tuple<Args...>& t1);

Inside this function, I would like to create another tuple t2 such that every elements of t1 is copied into t2 at the same position, except for elements of type A, for which t2 should create an object of type B (the constructor of B takes a reference to an object of type A).

Example: from the std::tuple containing 42, a1, 3.3, a3 (where a1 and a3 are instances of A) I want to build the std::tuple containing 42, b1, 3.3, b3 where b1 has been built from a1 and b3 from a3.

How can I do that? Thanks

free memory vector of smart pointers

i am a C++ beginner and just started using smart pointers of c++11. In my code i have a vector with std::unique_ptr to an Object called Partition (which i declared by myself).

I use this vector of partitions for a binary search and want to delete the vector and its partition upon end of the method.

As i understood, the unique_ptr is a smart pointer build around the usage in a single reference like my vector. If the vector cannot reference to the Partition anymore, the garbage collector will free the memory of the Partition object.

So far so good. But what is the correct way of removing the vector? Shall i just call it's clear method, and if so will this dereference the Partition object? Will there still be reserved memory for the vector?

Here is my Partition class

class Partition {
public:
    Partition(lemon::UnionFind components, std::vector<Graph::Node> v1, std::vector<Graph::Node> v2)
    : components(components), v1(v1), v2(v2) {}

    const lemon::UnionFind get_components() {
        return components;
    }

    const std::vector<Graph::Node> get_v1() {
        return v1;
    }

    const std::vector<Graph::Node> get_v2() {
        return v2;
    }

    bool is_activated() {
        return activated;
    }

    void mark() {
        this->marked = true;
    }

    void unmark() {
        this->marked = false;
    }

    void flip_activation_status(){
        this->activated = !this->marked;
    }


private:
    lemon::UnionFind components;
    std::vector<Graph::Node> v1;
    std::vector<Graph::Node> v2;
    bool activated;
    bool marked;
};

and here the binary search method which receives a vector of unique_ptr and should release the partitions as well as the reserved memory for the vector afterwards.

std::vector<Graph::Node> binary_fvs_search(std::vector<std::unique_ptr<Partition>> partitions, Graph graph) {

        // get lower bound
        int left = 0; // todo from lower bound

        // get upper bound
        int right = 10; // todo from upper bound

        int middle = (int) (left + floor((right - left) / 2));

        // helper variables
        bool found_solution;
        int best_result_length = std::numeric_limits<int>::max();
        std::vector<Graph::Node> result;
        std::vector<Graph::Node> best_result;

        // as long as we have searchspace left between left and right
        while(left < right){
            // init best result to 0 and found solution to false for this iteration
            best_result_length = 0;
            found_solution = false;

            // cycle through all partitions
            for(std::vector<std::unique_ptr<Partition>>::iterator p = partitions.begin(); p != partitions.end(); p++){
                // only feedback activated partitions
                if((**p).is_activated()) {

                    // call feedback on this partition and the current k = middle
                    // if feedback cannot find a solution it throws value = 0
                    try {
                        result = feedback(graph, (**p).get_v1(), (**p).get_v2(), (**p).get_components(), middle);
                    } catch (int value) {
                        // no solution for feedback mark partition to deactivate
                        if(value == 0) {
                            (**p).mark();
                        }
                        continue;
                    }

                    // tell flag that we found a solution for k = middle
                    found_solution = true;

                    // remember best result
                    if(result.size() < best_result_length) {
                        best_result = result;
                    }
                }
            }

            // we found a solution for k = middle
            if(found_solution) {
                // deactivate all marked partitions
                for(std::vector<std::unique_ptr<Partition>>::iterator p = partitions.begin(); p != partitions.end(); p++)
                {
                    (**p).flip_activation_status();
                }

                // change borders and middle
                right = left;
                middle = (int) (left + floor((right - left) / 2));
            }
        }

        // clear the partitions
        partitions.clear();
        return best_result;
    }

any feedback on this code is appreciated.

best, rap3

Does std::vector have a { Initial number of elements} constructor?

In cplusplus reference, Perhabs there is not { initial number of elements } constructor. The example is like below.

vector<string> svec { 5 }; 
cout << svec.capacity() << endl; // log is 5

But, there is explicit vector (size_type n); constructor. In this case, this is not { } brace. What happened to this statement ?

make fails with error "cannot convert ‘std::istream {aka std::basic_istream

I'm trying to compile libgtextutils (required by the fastxtoolkit) from source. The './configure' command runs nicely, however subsequent 'make' command produces an error that I cannot resolve.

text_line_reader.cpp: In member function ‘bool TextLineReader::next_line()’:
text_line_reader.cpp:47:9: error: cannot convert ‘std::istream {aka std::basic_istream<char>}’ to ‘bool’ in return
  return input_stream ;
         ^~~~~~~~~~~~
make[3]: *** [text_line_reader.lo] Error 1
make[2]: *** [all-recursive] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2

I'm on a Mac, OSX 10.11.6 (Intel)

Any suggestions that might solve this are highly appreciated.

Why console app hangs when using a shared dll that containg static variable that use mutex?

I have a shared dll library that contains a class as below :

inside A.dll >> Header File :

class API ErrorHandler  
{
public:
    ErrorHandler();

    virtual ~ErrorHandler();
protected:  
    static ErrorHandler* defaultHandler();

private:
    static ErrorHandler* _pHandler;
    static std::mutex     _mutex;
};

source(.cpp)

ErrorHandler* ErrorHandler::_pHandler = ErrorHandler::defaultHandler();
std::mutex ErrorHandler::_mutex;


ErrorHandler::ErrorHandler()
{
}


ErrorHandler::~ErrorHandler()
{
}

ErrorHandler* ErrorHandler::defaultHandler()
{   
    static SingletonHolder<ErrorHandler> sh;
    return sh.get(); **<<====== here we get hanged** see the declaration of get
}

SingletoneHolder header file

template <class S>
class SingletonHolder
{
public:
    SingletonHolder():
        _pS(0)
    {
    }

    ~SingletonHolder()
    {
        delete _pS;
    }

    S* get()
    {
        std::lock_guard<std::mutex> lock(_m); <===== cause thread hang
        if (!_pS) _pS = new S;

        return _pS;
    }

private:
    S* _pS;
    std::mutex _m;
};

After building the above code (every thing related to compiler setting configured correctly) now I want to use it in my console app.

After running console app, app hangs and never reach to main function.

Why std::lock_guard<std::mutex> lock(_m); hangs and prevent main thread to continue executing?

What is alternative?

I am using VS2013 Update5.

c++ class for storing any class from class hierarchy

let's suppose i have class hierarchy. A; B1,B2,B3-Bn all derived from A, and some C classes derived from differrent B's. I want to have a class "UnifiedStorage" to store A derived classes, that should not be templated, but it should have std::shared_ptr inside himself and have two functions:

template <typename T>
setData(std::shared_ptr<T> data/* A's derived class */)

template <typename T>
std::weak_ptr<T> getData()

only possible realization i have found is to create smth like Keeper:

class UnifiedStorage{
    class Keeper {
    public:
        virtual ~Keeper (){
        }
    };

    template <typename DataType>
    class SpecificKeeper : public Keeper {
    public:
        SpecificKeeper (std::shared_ptr<DataType> data): data(data) {}
        ~SpecificKeeper() = default;
        std::shared_ptr<DataType> data;
    };

    template <typename SpecificDataType>
    void setData (std::shared_ptr <SpecificDataType> d) {
        keeper.reset( new SpecificKeeper <SpecificDataType> (d) );
    }
    template <typename RequestedDataType>
    std::shared_ptr <RequestedDataType> getData () {
        SpecificKeeper <RequestedDataType>* specificKeeper =  dynamic_cast <SpecificKeeper <RequestedDataType> * > (keeper.data());
        if (specificKeeper == nullptr){
            return std::shared_ptr <RequestedDataType> ();
        }else{
            return specificKeeper->data;
        }
    }

    private:
        std::unique_ptr<Keeper> keeper;
}

But this realization has strong negative. I only able to get shared_ptr to type that i have set in setData.

For example if a have called setData<B>(std::shared_ptr<B>) i can't getData<A> it returns null, but if I will call setData<A>(std::shared_ptr<B>) getData<A> will return correct pointer.

std::unordered_map

When I declare a variable of std::unordered_map<boost::any, boost::any> type, it throws annoying compile errors.

For an example, any.cc:

#include <map>
#include <boost/any.hpp>

int main() {
    std::map<boost::any, boost::any> dict;
    return 0;
}

Compiling above code as g++ any.cc -std=c++11 -I/usr/include/boost occurs a lot of errors like following:

In file included from /usr/include/c++/5/bits/hashtable.h:35:0,
                 from /usr/include/c++/5/unordered_map:47,
                 from any.cc:1:
/usr/include/c++/5/bits/hashtable_policy.h: In instantiation of ‘struct std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> >’:
/usr/include/c++/5/type_traits:137:12:   required from ‘struct std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > >’
/usr/include/c++/5/type_traits:148:38:   required from ‘struct std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
/usr/include/c++/5/bits/unordered_map.h:100:66:   required from ‘class std::unordered_map<boost::any, boost::any>’
any.cc:5:48:   required from here
/usr/include/c++/5/bits/hashtable_policy.h:85:34: error: no match for call to ‘(const std::hash<boost::any>) (const boost::any&)’
  noexcept(declval<const _Hash&>()(declval<const _Key&>()))>
                                  ^
In file included from /usr/include/c++/5/bits/move.h:57:0,
                 from /usr/include/c++/5/bits/stl_pair.h:59,
                 from /usr/include/c++/5/utility:70,
                 from /usr/include/c++/5/unordered_map:38,
                 from any.cc:1:
/usr/include/c++/5/type_traits: In instantiation of ‘struct std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’:
/usr/include/c++/5/bits/unordered_map.h:100:66:   required from ‘class std::unordered_map<boost::any, boost::any>’
any.cc:5:48:   required from here
/usr/include/c++/5/type_traits:148:38: error: ‘value’ is not a member of ‘std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > >’
     : public integral_constant<bool, !_Pp::value>
                                      ^
In file included from /usr/include/c++/5/unordered_map:48:0,
                 from any.cc:1:
/usr/include/c++/5/bits/unordered_map.h: In instantiation of ‘class std::unordered_map<boost::any, boost::any>’:
any.cc:5:48:   required from here
/usr/include/c++/5/bits/unordered_map.h:100:66: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef __umap_hashtable<_Key, _Tp, _Hash, _Pred, _Alloc>  _Hashtable;
                                                                  ^
/usr/include/c++/5/bits/unordered_map.h:107:45: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::key_type key_type;
                                             ^
/usr/include/c++/5/bits/unordered_map.h:108:47: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::value_type value_type;
                                               ^
/usr/include/c++/5/bits/unordered_map.h:109:48: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::mapped_type mapped_type;
                                                ^
/usr/include/c++/5/bits/unordered_map.h:110:43: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::hasher hasher;
                                           ^
/usr/include/c++/5/bits/unordered_map.h:111:46: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::key_equal key_equal;
                                              ^
/usr/include/c++/5/bits/unordered_map.h:112:51: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::allocator_type allocator_type;
                                                   ^
/usr/include/c++/5/bits/unordered_map.h:117:45: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::pointer  pointer;
                                             ^
/usr/include/c++/5/bits/unordered_map.h:118:50: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::const_pointer const_pointer;
                                                  ^
/usr/include/c++/5/bits/unordered_map.h:119:47: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::reference  reference;
                                               ^
/usr/include/c++/5/bits/unordered_map.h:120:52: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::const_reference const_reference;
                                                    ^
/usr/include/c++/5/bits/unordered_map.h:121:46: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::iterator  iterator;
                                              ^
/usr/include/c++/5/bits/unordered_map.h:122:51: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::const_iterator const_iterator;
                                                   ^
/usr/include/c++/5/bits/unordered_map.h:123:51: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::local_iterator local_iterator;
                                                   ^
/usr/include/c++/5/bits/unordered_map.h:124:57: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::const_local_iterator const_local_iterator;
                                                         ^
/usr/include/c++/5/bits/unordered_map.h:125:47: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::size_type  size_type;
                                               ^
/usr/include/c++/5/bits/unordered_map.h:126:52: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       typedef typename _Hashtable::difference_type difference_type;
                                                    ^
/usr/include/c++/5/bits/unordered_map.h:280:7: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       operator=(initializer_list<value_type> __l)
       ^
/usr/include/c++/5/bits/unordered_map.h:379:2: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
  emplace(_Args&&... __args)
  ^
/usr/include/c++/5/bits/unordered_map.h:432:7: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       insert(const value_type& __x)
       ^
/usr/include/c++/5/bits/unordered_map.h:439:2: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
  insert(_Pair&& __x)
  ^
/usr/include/c++/5/bits/unordered_map.h:499:7: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       insert(initializer_list<value_type> __l)
       ^
/usr/include/c++/5/bits/unordered_map.h:645:7: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       equal_range(const key_type& __x)
       ^
/usr/include/c++/5/bits/unordered_map.h:649:7: error: ‘value’ is not a member of ‘std::__not_<std::__and_<std::__is_fast_hash<std::hash<boost::any> >, std::__detail::__is_noexcept_hash<boost::any, std::hash<boost::any> > > >’
       equal_range(const key_type& __x) const
       ^

But when I use boost::unordered_map rather than std, it works without any errors.

Why?