mardi 31 mars 2015

thread based memory usage statistic

The project I am working on needs a thread-based memory usage statistic function.


Ideally, I would like to implement this function in C++11 using with any third party library such as boost if available.


It needs to be able to collect the overall memory usage of the calling thread.


Concurrent write to different buckets in unordered_map (C++)?

C++ newbie here. I'm trying to write to different buckets concurrently in an unordered_map. From what I can tell by searching, it is my understanding that this should be a thread safe operation. My (perhaps incorrect) understanding is based on the answers here and here, as well as the referenced portion of the C++11 standard (particularly item 2 -- emphasis mine):



23.2.2 Container data races [container.requirements.dataraces]


1 For purposes of avoiding data races (17.6.5.9), implementations shall consider the following functions to be const: begin, end, rbegin, rend, front, back, data, find, lower_bound, upper_bound, equal_range, at and, except in associative or unordered associative containers, operator[].


2 Notwithstanding (17.6.5.9), implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting vector<bool>, are modified concurrently.


3 [ Note: For a vector x with a size greater than one, x[1] = 5 and *x.begin() = 10 can be executed concurrently without a data race, but x[0] = 5 and *x.begin() = 10 executed concurrently may result in a data race. As an exception to the general rule, for a vector < bool > y, y[0] = true may race with y[1] = true. —end note ]



In any case, it seems that writing to different buckets is not thread safe with the standard containers, as demonstrated by the code below. You'll see that I enable a lock corresponding to the bucket being modified before writing, yet sometimes pairs do not get recorded correctly. For what it's worth, if I use a single lock -- e.g., just change auto bkt = mm->bucket(key); to auto bkt=0;, effectively locking the entire unordered_map container -- everything works as expected.



#include <iostream>
#include <unordered_map>
#include <atomic>
#include <vector>
#include <thread>

#define NUM_LOCKS 409
#define N 100
#define NUM_THREADS 2

using namespace std;


class SpinLock
{
public:
void lock()
{
while(lck.test_and_set(memory_order_acquire)){}
}
void unlock()
{
lck.clear(memory_order_release);
}

private:
atomic_flag lck = ATOMIC_FLAG_INIT;
};


vector<SpinLock> spinLocks(NUM_LOCKS);


void add_to_map(unordered_map<int,int> * mm, const int keyStart, const int keyEnd, const int tid){

for(int key=keyStart;key<keyEnd;++key){
auto bkt = mm->bucket(key);

//lock bucket
spinLocks[bkt].lock();

//insert pair
mm->insert({key,tid});

//unlock bucket
spinLocks[bkt].unlock();
}

}


int main() {

int Nbefore, Nafter;
thread *t = new thread[NUM_THREADS];

//create an unordered map, and reserve enough space to avoid a rehash
unordered_map<int,int> my_map;
my_map.reserve(2*NUM_THREADS*N);

//count number of buckets to make sure that a rehash didn't occur
Nbefore=my_map.bucket_count();


// Launch NUM_THREADS threads. Thread k adds keys k*N through (k+1)*N-1 to the hash table, all with associated value = k.

for(int threadID=0;threadID<NUM_THREADS;++threadID){
t[threadID]=thread(add_to_map,&my_map,threadID*N,(threadID+1)*N,threadID);
}

// Wait for the threads to finish
for(int threadID=0;threadID<NUM_THREADS;++threadID){
t[threadID].join();
}

//count number of buckets to make sure that a rehash didn't occur
Nafter=my_map.bucket_count();


cout << "Number of buckets before adding elements: " << Nbefore <<endl;
cout << "Number of buckets after adding elements: " << Nafter << " <--- same as above, so rehash didn't occur" <<endl;

//see if any keys are missing
for(int key=0;key<NUM_THREADS*N;++key){

if(!my_map.count(key)){

cout << "key " << key << " not found!" << endl;

}
}

return 0;
}


The program will exit when a key was erroneously not entered. A sample output is:



Number of buckets before adding elements: 401
Number of buckets after adding elements: 401 <--- same as above, so rehash didn't occur
key 0 not found!
key 91 not found!
key 96 not found!
key 97 not found!
key 101 not found!
key 192 not found!
key 193 not found!
key 195 not found!


So, my question is two-fold:

1. Am I doing something wrong in how I am locking the buckets?

2. If so, is there a better way to lock the map on a bucket-by-bucket basis to enable concurrent writes to different buckets?


Finally, I'll mention that I already tried TBB's concurrent_unordered_map, but it was much slower in my application than simply doing things in serial. The stray errors aside, my bucket-locking approach using std::unordered_map performed significantly better.


ternary operator of different types

The following piece of code behaves differently under g++ 4.9.2 and clang++ 3.7.0. Which one is correct? What part in standard is related to this? Thanks.



#include <iostream>
using namespace std;

struct Base {
Base() = default;
Base(const Base&) = default;
Base(Base&&) = delete;
};

struct Derived : Base {
};

int main() {
const Base& b = true ? Derived() : Base();
}


g++ accepts it and clang++ gives an error incompatible operand types ('Derived' and 'Base'). See below for details.



[hidden]$ g++ -v
Using built-in specs.
COLLECT_GCC=/usr/bin/g++
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.9.2/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://ift.tt/1fOljwq --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --enable-multilib --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-linker-hash-style=gnu --enable-languages=c,c++,objc,obj-c++,fortran,ada,go,lto --enable-plugin --enable-initfini-array --disable-libgcj --with-isl=/builddir/build/BUILD/gcc-4.9.2-20150212/obj-x86_64-redhat-linux/isl-install --with-cloog=/builddir/build/BUILD/gcc-4.9.2-20150212/obj-x86_64-redhat-linux/cloog-install --enable-gnu-indirect-function --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
Thread model: posix
gcc version 4.9.2 20150212 (Red Hat 4.9.2-6) (GCC)
[hidden]$ g++ -std=c++11 b.cpp
[hidden]$ clang++ -v
clang version 3.7.0 (http://ift.tt/1n0Utol 6bbdbba8ec8a7730c68fee94363547dc2dc65b10)
Target: x86_64-unknown-linux-gnu
Thread model: posix
Found candidate GCC installation: /usr/lib/gcc/x86_64-redhat-linux/3.4.6
Found candidate GCC installation: /usr/lib/gcc/x86_64-redhat-linux/4.9.2
Selected GCC installation: /usr/lib/gcc/x86_64-redhat-linux/4.9.2
Candidate multilib: .;@m64
Candidate multilib: 32;@m32
Selected multilib: .;@m64
[hidden]$ clang++ -std=c++11 b.cpp
b.cpp:14:24: error: incompatible operand types ('Derived' and 'Base')
const Base& b = true ? Derived() : Base();
^ ~~~~~~~~~ ~~~~~~
1 error generated.

How to define a template class for a linked list node with pointer as template type

How to define a node template for a linked list? I also want to keep the pointer type as template parameter so that I can change it to unique_ptr or shared_ptr depends on what available.



template<typename T, typename NodePtr>
struct node{
T data;
NodePtr parent = nullptr;
};


The question is that how to initiate this class so that Nodeptr will be shared_ptr < Node <T ,what?> > type?


Perfect forwarding to multiple constructors

I'm really happy with the perfect forwarding in C++11 and want to do something more complicated. It's somewhat a classic case. I have a template axis-aligned box class. The template argument is a vector class. So I have a classic constructor, that takes 2 vectors:



template <class T> struct base_vec2 {
typedef T scalar_type;
base_vec2 (T a, T b); // counsruct for two scalar calues
};
template <class T> struct base_vec3 {
typedef T scalar_type;
base_vec2 (T a, T b, T c); // counsruct for three scalar calues
};
template <class T> struct base_box {
typedef typename T::scalar_type scalar_type;
T lower, upper; //<! upper and lower point
base_box<T> (const T& min, const T& max);
};
base_box<base_vec3<float>> box;


Naturally, one may want to implement a constructor which takes n scalar values and pass them to the lower and upper constructors. This is what I came up with:



template <class T> struct base_box {
.....
template <typename... Ts> base_box<T> (scalar_type s1, scalar_type s2, scalar_type s3, scalar_type s4, Ts&&... ts) {
base_box_construct<T, scalar_type, (4 + sizeof...(ts))/2> _(lower, upper, s1, s2, s3, s4, stl::forward<Ts>(ts)...);
}
};

base_box<base_vec2<float>> box(1, 2, 3, 4);
base_box<base_vec3<float>> box(1, 2, 3, 4, 5, 6);


base_box_construct do the actual magic:



template <class T, class A>
struct base_box_construct<T, A, 2> {
template <typename... Ts>
base_box_construct(T& lower, T& upper, A s1, A s2, A s3, A s4, Ts&&... ts)
{
lower = T(a1, a2);
upper = T(a3, a4);
}
};

template <class T, class A>
struct base_box_construct<T, A, 3> {
template <typename... Ts>
base_box_construct(T& lower, T& upper, A s1, A s2, A s3, A s4, Ts&&... ts)
{
lower = T(s1, s2, s3);
upper = T(s4, stl::forward<Ts>(ts)...);
}
};

template <class T, class A>
struct base_box_construct<T, A, 4> {
template <typename... Ts>
base_box_construct(T& lower, T& upper, A s1, A s2, A s3, A s4, Ts&&... ts)
{
lower = T(s1, s2, s3, s4);
upper = T(stl::forward<Ts>(ts)...);
}
};


It's a bit tricky, since it works only with 2, 3 and 4 arguments per vector which is just what I need. But I was wondering if there is better way to implement it.


Why s std::hash not specialised for std::reference_wrapper?

I thought it would have been, but I can't find this in my standard library implementation (gcc-4.8.2).


Why is std::hash not already specialised for std::reference_wrapper?



#pragma once
#include <functional>

namespace std
{
template<typename T>
struct hash<reference_wrapper<T>>
{
size_t operator()(const reference_wrapper<T>& r) const
{
return std::hash<T>()(r.get());
}
};
}

Consider the code



#include <vector>

int main()
{
std::vector<const int> vec;
}


According to Does C++11 allow vector<const T>? the code should not compile, even if in C++11 the vector elements are not required any more to be copy-assignable (now it only seems to be a requirement on the allocator). g++4.9 and g++5 reject the code, however clang (LLVM 3.5) merrily compiles it, with no warnings whatsoever.


I am not an expert in the standard, and would like to know what is the correct behaviour here?


Botan 1.10.9 SecureVector to std::vector bad_alloc

I have this strange error in botan 1.10.9. When I want to store the private key bytes vector and the publics key byte vector i get an std::bad_alloc error. Could it be that is not possible to initialize a std::vector from the SecureVector from botan?



Botan::LibraryInitializer init;

Botan::AutoSeeded_RNG rng;
rng.reseed(10096);

Botan::RSA_PrivateKey rsaPrivate(rng, 1024);

std::vector<unsigned char> privateArray(rsaPrivate.pkcs8_private_key().begin(), rsaPrivate.pkcs8_private_key().end());
std::vector<unsigned char> publicArray(rsaPrivate.x509_subject_public_key().begin(), rsaPrivate.x509_subject_public_key().end());


If i encode the keys, then the operation works fine:



Botan::SecureVector<Botan::byte> publicBytes = std::move(Botan::X509::BER_encode(rsaPrivate));
Botan::SecureVector<Botan::byte> privateBytes = std::move(Botan::PKCS8::BER_encode(rsaPrivate, rng, info.passphrase()));

std::vector<unsigned char> publicArray(publicBytes.begin(), publicBytes.end());
std::vector<unsigned char> privateArray(privateBytes.begin(), privateBytes.end());


Any ideas why this could be happening? The weird thing is that if i remove one of the vectors initialization, soooooometimes it works but most of the time i get the crash.


C++11 async - is management of optimal number of threads automatic?

If I have a task which spawns, say, 10,000 async threads using c++11 async<> / futures. Does async automatically manage the number of concurrent threads?


Specifically, if I have an 8 core machine, would my program spawn 10,000 thread or would it be smart enough to queue them up into batches of 8 (or whatever is ideal for my machine)?


Passing a temporary as a reference

I am currently trying to understand the copy and swap idiom through this post. The answer posted has the following code in it



class dumb_array
{
public:
// ...

friend void swap(dumb_array& first, dumb_array& second) // nothrow
{
// enable ADL (not necessary in our case, but good practice)
using std::swap;

// by swapping the members of two classes,
// the two classes are effectively swapped
swap(first.mSize, second.mSize);
swap(first.mArray, second.mArray);
}

// move constructor
dumb_array(dumb_array&& other)
: dumb_array() // initialize via default constructor, C++11 only
{
swap(*this, other); //<------Question about this statement
}

// ...
};


I noticed that the author used this statement



swap(*this, other);


other is a temporary or a rvalue which is being passed as a reference to the method swap. I was not sure if we could pass a rvalue by reference. In order to test this I tried doing this however the following does not work until i convert the parameter to a const reference



void myfunct(std::string& f)
{
std::cout << "Hello";
}

int main()
{
myfunct(std::string("dsdsd"));
}


My question is how can other being a temporary be passed by reference in swap(*this, other); while myfunct(std::string("dsdsd")); cant be passed by reference.


Intercepting sleep calls in C++

Is there a way to intercept calls to sleep and sleep-like functions in C++? I'd love to be able to replace the implementation with a no-op or in the alternative, multiply the sleep time. I imagine this would aid in determining correctness of concurrent programs as well as identifying a source of flakiness in tests.


I'm operating on a gigantic codebase, so using a wrapper function would be less satisfactory. Maybe there's a way to use ptrace or the same techniques that programs like valgrind use to intercept malloc?


Dynamically load gtkmm objects with dlopen

I have to dynamically use my library that uses Gtkmm. Unfortunately, I don't even manage to open a window in that way, and I don't understand why. Due to technical restrictions, the functions I must use are the dl* family. Here is what I have tried so far :


My compile lines:


for the library:



g++ gtkmm.cpp -shared -fPIC -o lib.so `pkg-config gtkmm-3.0 --cflags --libs


for the main:



g++ main.cpp -ldl


file: main.cpp



#include "INibbler.hpp"
#include <dlfcn.h>
#include <cstdlib>
#include <iostream>

typedef INibbler *(*fPtr)(int x, int y);

int main(int ac, char **av)
{
void *handle;
fPtr ptr;

handle = dlopen("./lib.so", RTLD_LAZY);
if (handle != NULL)
{
ptr = reinterpret_cast<fPtr>(dlsym(handle, "returnInstance"));
INibbler *test = reinterpret_cast<INibbler *>((*ptr)(700, 500));
test->loopGame(ac, av);
}
}


file: gtkmm.cpp



LibGtkmm::LibGtkmm(int x, int y)
{
(void)x;
(void)y;
this->set_default_size(100, 100);
}

LibGtkmm::~LibGtkmm()
{

}

void LibGtkmm::loopGame(int ac, char **av)
{
Glib::RefPtr<Gtk::Application> app
= Gtk::Application::create(ac,av, "org.gtkmm", Gio::APPLICATION_HANDLES_OPEN);

app->run(*this);
}

extern "C"
{
INibbler *returnInstance(int x, int y)
{
std::cout << "hey" << std::endl;
return (new LibGtkmm(x, y));
}
}


file: gtkmm.hpp



#ifndef GTKMM_H_
#define GTKMM_H_

#include <gtkmm.h>
#include "../INibbler.hpp"

class LibGtkmm : public INibbler, public Gtk::Window
{
private:
public:
LibGtkmm(int x, int y);
virtual ~LibGtkmm();
virtual void loopGame(int ac, char **av);
};

#endif // !GTKMM_H_


file: INibbler.hpp



#ifndef INIBBLER_HPP_
# define INIBBLER_HPP_

class INibbler
{
public:
virtual void loopGame(int ac, char **av) = 0;
};

#endif /* !INIBBLER_HPP_ */


When I call app->run, the window does not open itself, and I got a lot of GTK fail messages... telling that the pointer is somehow NULL. Here are the most notable:



(process:7556): Gtk-CRITICAL **: gtk_settings_get_for_screen: assertion 'GDK_IS_SCREEN (screen)' failed

(process:7556): GLib-GObject-WARNING **: invalid (NULL) pointer instance

(process:7556): GLib-GObject-CRITICAL **: g_signal_connect_object: assertion 'G_TYPE_CHECK_INSTANCE (instance)' failed


Does someone have an idea of how I can resolve my problem ?


When is the destructor of the temporary called

I wanted to know when the destructor of a temporay is called for both C++03 and C++11


Suppose I have the following case



foo method()
{
foo f;
......
......
return foo;
}

void doSomething()
{
foo f = method();
....
}


Suppose I am using the flag -fno-elide-constructors since I would like to get a theoretical understanding of when the destructor of a temporary is called. So from the above code in C++03 when the method() is finished a copy of foo is made using its copy constructor. After that at the statement foo f = method() the copy constructor of foo is called again. In this case for C++03 when is the destructor of this tempoary (which was passed by method) called ? Is it called at the end of scope of doSomething() Now I would like to apply the same case to C++11 which involve the move semantics. In case of C++11 when method returns a copy of foo is made.Then when foo f = method() is called the move constructor of foo is called. So in case of C++11 when is the destructor of the temporary object returned from method() called ?


python csv reader ignore commas within brackets

I have comma separated values that contain commas within nested brackets. Specifically, I'll have an input of comma separated C++11 objects (correct commas starred for emphases):



std::vector<int>{32, 45, 10} *,*
std::array<std::string, 5>{"a", "bc", "def", "ghij", "whoa, this is, a toughie"} *,*
8 *,*
"foo, bar" *,*
{"initializer-list?", "no problem!", "(hopefully...)"


But python's csv gives me:



[
'std::vector<int>{32',
'45',
'10}',
'std::array<std::string',
'5>{"a"',
'"bc"',
'"def"',
'"ghij"',
'"whoa',
'this is',
'a toughie"}',
'8',
'"foo',
'bar"',
'{"initializer-list?"',
'"no problem!"',
'"(hopefully...)"}'
]


How can I customize the csv module to handle these cases?


why shouldn't these conditions work for template types?

As my previous question i am trying to build a conditions to examine two types check if should i do dynamic_cast or not. I had following conditions:



#define can_dynamic_cast(FROM, TO) \
can_cast(FROM, TO) && \
!std::is_same<FROM, TO>::value && \
std::is_class<TO>::value && \
!std::is_const<FROM>::value && \
std::is_base_of<TO, FROM>::value


It does not work for below basic check, the can_dynamic_cast will return true!!!



static_assert(!can_dynamic_cast(int, int), "didn't expecting dynamic cast, but could!")


Out of desperation i came down to below conditions, but still no hope!!



#define can_dynamic_cast(FROM, TO) \
std::is_convertible<FROM, TO>::value && \
std::is_class<TO>::value && \
std::is_class<FROM>::value


The above conditions are the most basic conditions, can_dynamic_cast will return true for (int, int) again, which is not suppose to!!!


Question


1) What am i don't wrong?


Hiding members in public interface and ODR

I have multiple classes in a library that have internals that I wish to hide from client code. From the client's perspective, each class is queried from a library class and is only used as an opaque pointer. An example is as follows:



struct SomeSystem;
void doSomethingToSomeSystem(SomeSystem* system, Parameters params);
void doSomethingElseToSomeSystem(SomeSystem* system, Parameters params);


On the implementation side, SomeSystem has multiple members which are not visible to the caller. This is all fine but I don't really like the clunky usage syntax:



SomeSystem* system = lib->getSomeSystem();
doSomethingToSomeSystem(system, params);
doSomethingElseToSomeSystem(system, params);


Another approach is this:



struct SomeSystem;
namespace somesystem {
void doSomething(SomeSystem* system, Parameters params);
void doSomethingElse(SomeSystem* system, Parameters params);
}


With the usage code:



SomeSystem* system = lib->getSomeSystem();
somesystem::doSomething(system, params);
somesystem::doSomethingElse(system, params);


I could also use global methods called doSomething and doSomethingElse and depend on function overloading if another type also defines doSomething. However, in this case, it is hard to find all "members" of SomeSystem in an IDE.


I am tempted to actually use member functions:



struct SomeSystem {
void doSomething(Parameters params);
void doSomethingElse(Parameters params);
};


With the usage code:



SomeSystem* system = lib->getSomeSystem();
system->doSomething(params);
system->doSomethingElse(params);


The last snippet looks good to me but SomeSystem is no longer an opaque pointer - it actually defines members. I'm a bit wary of this. One potential problem is the one definition rule. However, the "public" definition and "private" definition of the class will only be visible to different translation units. Is there any other badness hidden here? If the client code tries to instantiate SomeSystem on the stack or using new it would obviously crash the program. But I'm willing to accept that. Perhaps I can get around this by providing a private constructor in the public interface.


Another approach is of course to define an abstract class with pure virtual methods. However, I would like to avoid the overhead of this in case it is not absolutely necessary.


get value from std::map in c++ which has custom type

I have initialized a map as:



typedef void* ProxyClientHandler;
std::map<string,ProxyClientHandler> connectedClient;


And I am inserting values into this map as



ProxyClientHandler client;
string device;
connectedClient.insert ( std::pair<string,ProxyClientHandler>(device,client) );


no error returns upto this.


But when i am going to access the value of given relevant key as



string deviceId;
ProxyClientHandler client = connectedClient.find(deviceId);


it gives me an error:



error: cannot convert ‘std::map, void*>::iterator {aka std::_Rb_tree_iterator, void*> >}’ to ‘ProxyClientHandler {aka void*}’ for argument ‘1’ to ‘int DHProxyClientDelPort(ProxyClientHandler, int)’



how can i fix this issue???


std::make_pair, c++11 and explicit template parameters

Can you tell me, what is exactly behind of this following problem? This code is a simple example working on c++03 and fails on c++11.



std::pair<int*,int**> getsth(int* param)
{
return std::make_pair<int*,int**>(param, 0);
}

int main(int argc, char* argv[])
{
int* a = new int(1);
std::pair<int*,int**> par = getsth(a);
std::cout << *par.first;
return 0;
}


I do know how to fix it to be compatible with both standards here, but it is annyoing me, that I don't know, what is exactly behind make_pair in this case.


Thanks!


edited: a compile error message from Coliru:



main.cpp: In function 'std::pair<int*, int**> getsth(int*)':
main.cpp:8:47: error: no matching function for call to 'make_pair(int*&, int)'
return std::make_pair<int*,int**>(param, 0);
^
main.cpp:8:47: note: candidate is:
In file included from /usr/local/include/c++/4.9.2/bits/stl_algobase.h:64:0,
from /usr/local/include/c++/4.9.2/bits/char_traits.h:39,
from /usr/local/include/c++/4.9.2/ios:40,
from /usr/local/include/c++/4.9.2/ostream:38,
from /usr/local/include/c++/4.9.2/iostream:39,
from main.cpp:1:
/usr/local/include/c++/4.9.2/bits/stl_pair.h:276:5: note: template<class _T1, class _T2> constexpr std::pair<typename std::__decay_and_strip<_Tp>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&)
make_pair(_T1&& __x, _T2&& __y)
^
/usr/local/include/c++/4.9.2/bits/stl_pair.h:276:5: note: template argument deduction/substitution failed:
main.cpp:8:47: note: cannot convert 'param' (type 'int*') to type 'int*&&'
return std::make_pair<int*,int**>(param, 0);
^
main.cpp:9:1: warning: control reaches end of non-void function [-Wreturn-type]
}

How to use shared_ptr in extern C when use python to call the so file?

I want to use C++ to make an so file on Linux,and use python to call the library.I use shared_ptr in extern C declare,compile success but get some error when call the library use python. I create some cpp files,like these: Calculator.h:



#ifndef HELLO_WORLD_CALCULATOR_H
#define HELLO_WORLD_CALCULATOR_H
class Calculator {
public:
double add(double first, double second);
};
#endif


Calculator.cpp:



#include "Calculator.h"
double Calculator::add(double first, double second) {
return first + second;
}


main.cpp:



#include <iostream>
#include <tr1/memory>
#include "Calculator.h"

using namespace std;

double devide1(double first, double second){
shared_ptr<Calculator>calculater(new Calculator());
return calculater->devide(first, second);
}

extern "C"
{
double devide(double f, double s){
return devide1(f,s);
}
}


And I compile the file use this command: g++ main.cpp -fPIC -shared -o test.so -std=c++11 My python file test.py:



# coding=utf-8

import ctypes
from ctypes import *

if __name__ == "__main__":
lib = ctypes.CDLL("./test.so")
lib.devide.argstype = [c_double, c_double]
lib.devide.restype = c_double
print lib.devide(c_double(12), c_double(36))


And I run the program use python test.py in terminal.Then I got the error:



Traceback (most recent call last):
File "test.py", line 9, in <module>
lib = ctypes.CDLL("./test.so")
File "/usr/lib/python2.7/ctypes/__init__.py", line 365, in __init__
self._handle = _dlopen(self._name, mode)
OSError: ./test.so: undefined symbol: _ZN10Calculator6devideEdd


How to fix the bug?


Visual C++ 2013 std::string memory leak

During development of proprietary app. I have noticed memory leak, related to std::string in a MS Visual C++ 2013, Update 4.


Take a look at the following (basic) code prototype which causes memory leak:



static std::string MemoryLeakTest()
{
static size_t const test_size = 2002;
std::unique_ptr<char[]> result1(new char[test_size]);
std::string result2(result1.get(), test_size);
return result2;
}


calling it by:



std::string const testML = MemoryLeakTest();
std::cout << testML << std::endl;


Am I doing something wrong, or is it a memory leak in a Visual C++ STL?


Should I use std::move on functions returning std::vector?

Consider this kind of a function:



std::vector<int> generateVector() {
return std::vector<int>(10, 0);
}


Are there any benefits in calling generateVector() like this:



std::vector<int> v = std::move(generateVector());


..or is this kind of a move optimization now automatically done by the compiler?


Intel C++ compiler: What is highest GCC version compatibility?

I am using the latest Intel C++ compiler, icpc 15.0.1 (2014-10-23). The -gxx-name compiler option indicates to icpc what gcc libraries and language compatibility the developer desires. However, the documentation does not list the maximum version number for gcc compatibility. Is 15.0.1 compatible with gcc 4.9.x? Please provide links to documentation if available.


C++ semantic error in structure variable

I am new to programming. I was trying to parse an input which contains the records of some people in a file in the following form:


5 dave laura owen vick amr dave 200 3 laura owen vick owen 500 1 dave amr 150 2 vick owen laura 0 2 amr vick vick 0 0


The first interger that is 5 represents the total number of persons involved, after which we get 5 strings upto amr. The next input involves a string "dave" and 2 integers 200 and 3 where 3 denotes the number of persons associated with "dave". The next 3 strings are the names of the person associated with "dave". Subsequent entires represent the same semantic structure.


I coded a "structure dict" to hold the above information, and stored the names of the persons in the struct variable 'name'. However as I retrieve the data from the file into the struct variables, my code automatically changes the information in the struct variables. I am unable to locate the error and would be very thankful if any of you could help me figure my mistake. Thanks in advance.



#include "iostream"
#include "fstream"
using namespace std;

typedef struct $
{
char name[14];
int dollars;
int no_Persons;
char friends[][14];
}dict;

int main()
{
ofstream fout ("gift1.out");
fstream fin ("gift1.in");
int num;
fin >> num;
dict NP[num];
int counter = num;
char name[14];
int index;
for(int i = 0; i < counter; i ++)
fin >> NP[i].name;
while(counter)
{
fin >> name;
for(int i = 0; i < num; i++)
{
if(strcmp(name, NP[i].name)==0)
{
index = i;
break;
}
}
fin >> NP[index].dollars;
fin >> NP[index].no_Persons;
for(int i = 0; i < NP[index].no_Persons; i ++)
fin >> NP[index].friends[i];

counter --;
}

for(int i = 0; i < num; i++)
{
cout << NP[i].name << endl;
cout << NP[i].dollars << " " << NP[i].no_Persons << endl;
for(int j = 0; j < NP[i].no_Persons; j++ )
cout << NP[i].friends[j] << endl;
}
}

Create matrix in c++. FOR statement alternative

I am trying to create a matrix in C++. I am a beginner. Is there any other simple way to done this? I am refering to the for statement which uses cin (something like for (i,j=1; i,j<=n; i,j++) or cin >> a;)



int n=5;
int a[n][n];

for(int i=1; i<=n; i++) {
for(int j=1; j<=n; j++) {
cin >> a[i][j];
}
}


Thanks!


C++11 thread support in large compilers

I need to know since when gcc and Intel C++ compiler support the C++11 style libraries thread, mutex, atomic (all together).


Or formulated differentely:

Since when can you compile the following without special flags:



#include <thread>
#include <mutex>
#include <atomic>

int main()
{
std::thread TestObject1;
std::atomic<int> TestObject2;
std::mutex TestObject3;
return;
}


Please also provide the compile-time-constant for the specific version.


I have a member function _wrapper in my class, that encapsulates some common logic around family of other functions. This wrapper function accepts pointer to function that is being wrapped and its arguments.


Wrapper in my class is implemented similar to how it is done in this example class Foo:



#include <functional>

class Foo
{
public:
void bar1(int a)
{
/// No-op.
}

void bar2(const int & a)
{
/// No-op.
}

void foo(int x)
{
_wrapper_bar1(x); /// No problems to deduce type
_wrapper_bar2(x); /// No problems to deduce type

_wrapper(&Foo::bar1, x); /// Deduction fails
_wrapper(&Foo::bar2, x); /// Deduction fails
}

private:
template <typename ...Args>
void _wrapper(void (Foo::*method) (Args ...), Args && ...args)
{
/// Do some common stuff here...

(this->*method(std::forward<Args>(args)...));
}

template <typename ...Args>
void _wrapper_bar1(Args && ...args)
{
bar1(std::forward<Args>(args)...);
}

template <typename ...Args>
void _wrapper_bar2(Args && ...args)
{
bar2(std::forward<Args>(args)...);
}
};

int main(int argc, char ** argv)
{
Foo().foo(123);
return 0;
}


When I pass an lvalue, foo's argument int x, to the wrapper, clang compiler complaints that there is a conflict and deduction fails:



test.cpp:21:9: error: no matching member function for call to '_wrapper'
_wrapper(&Foo::bar1, x); /// Deduction fails
^~~~~~~~
test.cpp:27:10: note: candidate template ignored: deduced conflicting types for parameter 'Args' (<int> vs. <int &>)
void _wrapper(void (Foo::*method) (Args ...), Args && ...args)
^
test.cpp:22:9: error: no matching member function for call to '_wrapper'
_wrapper(&Foo::bar2, x); /// Deduction fails
^~~~~~~~
test.cpp:27:10: note: candidate template ignored: deduced conflicting types for parameter 'Args' (<const int &> vs. <int &>)
void _wrapper(void (Foo::*method) (Args ...), Args && ...args)


The thing is I don't understand why is this happening. It is okay to pass just lvalue alone, as it is done using _wrapper_bar1 and _wrapper_bar2. And doing so does not rise any conflict of this sort, ie const T & vs T &.


I know a way around this error: by casting lvalue to an rvalue using std::move(x), but obviously it is not a fix, since move is not actually needed. Also, sometimes I need to use x after calling wrapper function, and using moved value is an UB.


Probably my template is very broken and I am missing some obvious thing. I'd appreciate your help.


std::bind not able to call the class member function: C++

I have to implement A valve Open function (for specified duration). I am using boost::asio::deadline_timer


My class member function to open valve is:



bool Valves::valveOpen(ValveType type)
{
switch (type)
{
case eVentValve:
tblMap_.digitalInput[eVentValveK1].setBit();
if (tblMap_.digitalOutput[eOutK1VentValve].getBit())
{
isVentOpen_ = true;
}
return isVentOpen_;

case eVacuumPumpValve:

....
....
}


Class member function to close the valve is:



bool Valves::valveClose(ValveType type)
{
switch (type)
{
case eVentValve:
tblMap_.digitalInput[eVentValveK1].clearBit();
if (!tblMap_.digitalOutput[eOutK1VentValve].getBit())
{
isVentOpen_ = false;
}
return !isVentOpen_;

case eVacuumPumpValve:
....
....
}


I am trying to achieve the timer action as below



bool Valves::valveTimedOpen(ValveType type, int sec)
{
boost::asio::io_service io;
switch (type)
{
case eVentValve:
{
std::bind(&Valves::valveOpen, this, type); //Here
boost::asio::deadline_timer t(io, boost::posix_time::seconds(sec));
t.async_wait(std::bind(&Valves::valveClose, this, type));
boost::thread th(boost::bind(&boost::asio::io_service::run, &io));
return true;
}

case eVacuumPumpValve:

.....
.....
}


The code hits the line Here i.e.


std::bind(&Valves::valveOpen, this, type); but it does not go to bool Valves::valveOpen(ValveType type) function.


Can someone let me know the issue with this code?


Select % of random numbers from list [on hold]

I'm interested in selecting a % of random numbers form a list. For example, if I have the following list: 1 2 3 4 5 6 7 8 9 10, I would want to select randomly 40% out of it and the returned list to be: 2 5 6 10 (which were selected randomly).


My final purpose will be to select a percentage of lines from a file in the same way.


Does anyone have any idea how could this be implemented?


Thanks


Failing in trying to code smart cast template function

I am currently trying to code a function to perform static_cast or dynamic_cast based on its input and output types in following of DRY principle. The function which i am trying to accomplish is as below:



#define where typename = typename
#define can_cast(FROM, TO) std::is_convertible<FROM, TO>::value
#define can_dynamic_cast(FROM, TO) \
can_cast(FROM, TO) && \
!std::is_same<FROM, TO>::value && \
std::is_class<TO>::value && \
!std::is_const<FROM>::value && \
std::is_base_of<TO, FROM>::value
#define can_static_cast(FROM, TO) can_cast(FROM, TO)

template<typename _Tout, typename _Tin, where
std::enable_if<
!std::is_pointer<_Tout>::value &&
!std::is_pointer<_Tin>::value &&
can_cast_ptr(_Tin, _Tout)>::type>
inline _Tout* gc_ptr_cast(_Tin* const p) {
if(can_dynamic_cast(_Tin*, _Tout*))
return dynamic_cast<_Tout*>(p);
if(can_dynamic_cast(_Tin*, _Tout*))
return static_cast<_Tout*>(p);
throw bad_cast();
}


But it won't work for for example gc_ptr_cast<int>(new int(1)) due to the complaining of compiler such that:



[..] error: cannot dynamic_cast 'p' (of type 'int* const') to type 'int*' (target is not pointer or reference to class) return dynamic_cast<_Tout*>(p)«;



The compiler should process static_cast instead of dynamic_cast!

Now i am not even sure if i am in correct path using <type_traits> for such purpose.


I have a half a thousand of template functions with in some of them i need to perform static_cast and in some of them i need to dynamic_cast and in half of the remaining i need to check both. The dynamic_cast are important in my case since it is successful in below example which is a crucial part to make things right!



struct base1 {};
struct base2 {};
struct derived : public base1, public base2 {};
.
.
.
derived obj;
base1* p1 = &obj;
base2* p2 = &obj;
assert(dynamic_cast<void*>(p1) == dynamic_cast<void*>(p2)); // will succeed
assert(static_cast<void*>(p1) == static_cast<void*>(p2)); // will fail [ THIS IS WHY I CANNOT USE `static_cast` IN SOME CASES ]


I know there is a smart cast of boost library, but i want my code just depend on C++11 std. library.


Questions


1) What am i doing wrong?

2) How do i accomplish gc_ptr_cast<>()?




P.S: Maybe i over did the some conditions, I have put in can_dynamic_cast but it's OK for now.


Can I create an empty range (iterator pair) without an underlying container object?

I have a class akin to the following:



struct Config
{
using BindingContainer = std::map<ID, std::vector<Binding>>;
using BindingIterator = BindingContainer::mapped_type::const_iterator;

boost::iterator_range<BindingIterator> bindings(ID id) const;
private:
BindingContainer m_bindings;
};


Since the ID passed to bindings() might not exist, I need to be able to represent a 'no bindings' value in the return type domain.


I was hoping to be able to do so with the interface as above and default-construct the iterators, but although a ForwardIterator is DefaultConstructible [N3337 24.2.5/1] the result of comparing a singular iterator is undefined [24.2.1/5], so without a container it seems this is not possible.


I could change the interface to e.g wrap the iterator_range in a boost::optional, or return a vector value instead; the former is a little more clunky for the caller though, and the latter has undesirable copy overheads.


Another option is to keep a statically-allocated empty vector and return its iterators. The overhead wouldn't be problematic in this instance, but I'd like to avoid it if I can.


Adapting the map iterator to yield comparable default-constructed iterators is a possibility, though seems over-complex...


Are there any other options here that would support returning an empty range when there is no underlying container?


(Incidentally I'm sure a while back I read a working paper or article about producing empty ranges for standard container type when there is no container object, but can't find anything now.)


(Note I am limited to C++11 features, though I'd be interested if there is any different approach requiring later features.)


Breadth first search. Output not dispaying correctly in c++

This is my assignment and i have completed the coding but not displaying the output correctly. The find function below and used in main also does not display and there is a memory leak when checked with valgrind ./a.out but does not tell me where the leak is. Help me out please



#include < map >
#include < queue >
#include < string >
#include < iostream >

using namespace std;

// trie_node

// Implements a trie. This version is hard-coded to use char. The

// end-of-sequence value is a map entry of { char{}, nullptr }.

// This permits char{} values to be within the string as no other

// map entries will have nullptr values stored in them in the entire

// trie.

// NOTE: Some functions are provided and some are not. You must write

// the missing code.

class trie_node
{

public:
using value_type = char;

`private:
using elem_type = char;
using child_node_type = trie_node*;

map< elem_type, child_node_type > children;

public:

// Default construction is simple: since the children map has a default
// constructor, no data is needed in it, and that is the only data
// member, let the compiler generate the code...

trie_node() = default;

// Copy construction performs a breadth-first search (BFS) of the trie

// being copied from. The BFS is tracked using a std::vector as a queue

// where the vector is a pair of trie_node*. The pair of trie_node*

// is used to simultaneously track the BFS in the source trie with the

// corresponding element in the BFS construction of the *this trie.

// Know that a BFS traversal of a tree uses a queue. Essentially, one

// visits a node, queues all its children, and then repeat processing

// the next element at the front of the queue until the queue is empty.

// For time reasons this code has been provided to you. Do take note

// how the solution is crafted using contrainers, etc.

trie_node( trie_node const& n )
{
// stack: breadth first search, std::pair< newtrie, oldtrie >

std::vector< std::pair<trie_node*, trie_node const*> > stack;
std::vector< std::pair<trie_node*, trie_node const*> > bfs;

// Start stack with ( this, &n )...

stack.emplace_back( this, &n );

do
{
auto curpos = stack.back(); bfs.pop_back();

// If this node has no children, then record such and loop...

if ( curpos.second == nullptr )
{
curpos.first = nullptr;
continue;
}

// Enumerate all children...

for (
auto i=begin( curpos.second->children ) ,
iEnd = end( curpos.second->children ) ;
i != iEnd;
++i
)

{
// Create the child trie_node iff i->second != nullptr.

// If i->second == nullptr then it is an end-of-sequence character.

trie_node* tmp_node{
( i->second != nullptr )
? new trie_node
: nullptr
};

// Copy the new node...

curpos.first->children.emplace(
i->first, tmp_node
);

// And continue updating the stack queue...

stack.emplace_back( tmp_node, i->second );
}
} while ( !stack.empty() );
}

// TODO: Write copy assignment operator.

// HINT: 1) Create a local trie_node variable as n is const.

// 2) Use swap.


trie_node& operator = ( trie_node const& n )
{
trie_node tmp( n );
swap( tmp );
return *this;

}

// TODO: Move constructor.

// HINT: There is only one data member. Try moving it! :-)

// RESTRICTION: No code must appear inside the { } braces.

trie_node( trie_node&& n ) : children(std::move(n.children)) {}


// TODO: Move assignment operator.

// HINT: The trie_node class has a swap() member function. Use it!

trie_node& operator =( trie_node&& n )

{
swap( n );
return *this;
}

// TODO: Destructor.

// HINT: The trie_node class has a clear() member function. Use it!

~trie_node()
{
clear();
}


// TODO: swap().

// HINT: You know how to swap variables using a temporary variable.

// Do exactly this.

// Now add std::move() around each variable on the right-hand

// side of each assignment operator. This will allow moves

// instead of copies where possible.


void swap( trie_node& n )
{
trie_node tmp = move( n ) ;

n = move( *this );

*this = move( tmp );

}



// TODO: clear()

// HINT: Like the copy constructor, clear() will traverse the trie

// using breadth-first search.

// Look up std::queue in your textbooks. You'll notice the

// functions: push(), pop(), front(), back(), and empty().

// Pseudocode is given in the task description within the
// project.

// RESTRICTION: You must use std::queue<trie_node*> to do this

// solution.


void clear()
{

std::queue<trie_node*> bfs;
bfs.push( this );


while(!bfs.empty())
{
trie_node* node_ptr ;

node_ptr = bfs.front();

bfs.pop();

for( auto i = bfs.front(); i != bfs.back() ; i++ )
{

if( node_ptr != nullptr )
{
bfs.push( node_ptr );
free( node_ptr );
}

}

bfs.pop();

if( node_ptr == this )
{
delete node_ptr;
}

}
}




// This is the code done in class for the add() function except

// support has been added to handle an end-of-sequence marker.

//

// NOTE: Notice the use of emplace() instead of insert().

// The emplace() function passes its arguments directly

// to the constructor of the std::pair in the map.

void add(std::string const& s)
{

// Start at this (root) node...

trie_node* curpos = this;

// Build trie for s...

for ( auto i=begin(s), iEnd=end(s); i != iEnd; ++i )
{
// Add the next sequence value...

// result's type: pair<iterator, bool>

auto result = curpos->children.emplace(elem_type(*i), nullptr);

// If the next sequence value was inserted, then ensure

// a default trie_node is allocated with new...

if ( result.second )
{
// *i is not already stored and next entry must at least

// be end-of-string...

result.first->second = new trie_node;
}

// Continue with next node's information...

curpos = result.first->second;
}

// When done adding the sequence, ensure there is an end-of-sequence

// value added...
curpos->children.emplace(elem_type{}, nullptr);
}

// This is the code done in class for the find() function except

// support has been added to handle an end-of-sequence marker.

bool find( std::string const& s ) const
{
bool retval = false;
trie_node const * curpos = this;

for (auto curvalue : s)
{
auto const sEnd = end(curpos->children);

auto iter = curpos->children.find(elem_type(curvalue));
if (iter != sEnd)
curpos = iter->second;
else
curpos = nullptr; // not found

if (curpos == nullptr)
return retval;
}

// If we get here, then the sequence is in the trie iff

// there is an end-of-sequence character...

auto result = curpos->children.find( elem_type{} );
if ( result != end( curpos->children ) && result->second == nullptr )
retval = true;

return retval;
}

// You might need to debug your code. Also you might wonder how

// to obtain every sequence in the trie. This recursive function

// shows how to do an inorder traversal of the trie. It will

// output all sequences to the basic_ostream os.

template <typename Ch, typename ChTr>
void print_inorder(
std::basic_ostream<Ch,ChTr>& os,
std::vector<elem_type> prefix={}
)
{
for ( auto&& child : this->children )
{
prefix.push_back( child.first );

if ( child.second != nullptr )
child.second->print_inorder( os, prefix );
else
{
auto i = begin( prefix );
auto iEnd = end( prefix );

// Discard the end of string marker...

if ( iEnd != i )
--iEnd;

// Output sequence...

for ( ; i != iEnd; ++i )
os << *i;
os << endl;
}

prefix.pop_back();
}
}
};

// TODO: swap()

// HINT: Simply invoke trie_node's swap()!

// NOTE: This is needed to support calling a free swap() function.

// One may or may not know about the member function --but one

// shouldn't have to know about it at all if this function is

// provided!

inline void swap( trie_node& a, trie_node& b )
{
swap( a , b );
}


int main()
{
trie_node n;

string test = "ab";

n.add( test );
n.add( string ( "abcde" ) );
n.add( string ( "abcdd" ) );
n.add( string ( "airplane" ) );
n.add( string ( "airlock" ) );
n.print_inorder( cout );

trie_node o = n;

bool b2 = o.find( string ( "airplane" ) );

bool b3 = o.find( string ( "airlock" ) );

bool b4 = o.find( string ( "a" ) );

cout << b2 << b3 << b4 << '\n';

// Outputs: 110

return 0;

}

Reimplementing std::swap() with static tmp variable for simple types C++

For some reason I decide to benchmark realization of swap function for simple types(like int, or struct and classes uses only simple types in its fields) with static tmp variable in it to prevent memory allocation in each swap call. So I wrote this simple test programm:



#include <iostream>
#include <chrono>
#include <utility>
#include <vector>


template<typename T>
void mySwap(T& a, T& b) //Like std::swap - just for tests
{
T tmp = std::move(a);
a = std::move(b);
b = std::move(tmp);
}

template<typename T>
void mySwapStatic(T& a, T& b) //Here with static tmp
{
static T tmp;
tmp = std::move(a);
a = std::move(b);
b = std::move(tmp);
}

class Test1 { //Simple class with some simple types
int foo;
float bar;
char bazz;
};

class Test2 { //Class with std::vector in it
int foo;
float bar;
char bazz;
std::vector<int> bizz;
public:
Test2()
{
bizz = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
}
};

#define Test Test1 //choosing class

const static unsigned int NUM_TESTS = 100000000;
static Test a, b; //making it static to prevent throwing out from code by compiler optimizations

template<typename T, typename F>
auto test(unsigned int numTests, T& a, T& b, const F swapFunction ) //test function
{
std::chrono::system_clock::time_point t1, t2;
t1 = std::chrono::system_clock::now();
for(unsigned int i = 0; i < NUM_TESTS; ++i) {
swapFunction(a, b);
}
t2 = std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count();
}

int main()
{
std::chrono::system_clock::time_point t1, t2;
std::cout << "Test 1. MySwap Result:\t\t" << test(NUM_TESTS, a, b, mySwap<Test>) << " nanoseconds\n"; //caling test function
t1 = std::chrono::system_clock::now();
for(unsigned int i = 0; i < NUM_TESTS; ++i) {
mySwap<Test>(a, b);
}
t2 = std::chrono::system_clock::now();
std::cout << "Test 2. MySwap2 Result:\t\t" << std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count() << " nanoseconds\n"; //This result slightly better then 1. why?!
std::cout << "Test 3. MySwapStatic Result:\t" << test(NUM_TESTS, a, b, mySwapStatic<Test>) << " nanoseconds\n"; //test function with mySwapStatic
t1 = std::chrono::system_clock::now();
for(unsigned int i = 0; i < NUM_TESTS; ++i) {
mySwapStatic<Test>(a, b);
}
t2 = std::chrono::system_clock::now();
std::cout << "Test 4. MySwapStatic2 Result:\t" << std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count() << " nanoseconds\n"; //And again - it's better then 3...
std::cout << "Test 5. std::swap Result:\t" << test(NUM_TESTS, a, b, std::swap<Test>) << " nanoseconds\n"; //calling test function with std::swap for comparsion. Mostly similar to 1...
return 0;
}


Some results with Test defined as Test1 (g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2 called as g++ main.cpp -O3 -std=c++11):



Test 1. MySwap Result: 625105480 nanoseconds


Test 2. MySwap2 Result: 528701547 nanoseconds


Test 3. MySwapStatic Result: 338484180 nanoseconds


Test 4. MySwapStatic2 Result: 228228156 nanoseconds


Test 5. std::swap Result: 564863184 nanoseconds



So here is main question - how do you think - is it good to use this implementation for simple types swapping? (I know that if you use it for swapping types with vectors for example - std::swap better, and u can see it just changing Test define to Test 2)


And second question - why results in test 1, 2 and 3, 4 so different? What I'm doing wrong with test function implementation?


P.S. Sorry for my bad English...


I need std::chrono::high_resolution_clock::time_point field which I want to write from one thread and read from another thread. If I declare it as is my code compiles without any errors.


But to make my field visible in another thread I surround it with std::atomic like this std::atomic<std::chrono::high_resolution_clock::time_point> and now I have following compilation error:



/usr/include/c++/4.8/atomic:167:7: error: function ‘std::atomic<_Tp>::atomic() [with _Tp = std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000000l> > >]’ defaulted on its first declaration with an exception-specification that differs from the implicit declaration ‘constexpr std::atomic<std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000000l> > > >::atomic()’
atomic() noexcept = default;


How should I declare std::chrono::high_resolution_clock::time_point field which I write from one thread and read from another (to make sure that "reading thread" sees last value)?


MACRO depending on its folder location

In the following files:



app/main.cpp
app/config.hpp
app/show.hpp
app/file.hpp

lib/append.hpp
lib/clear.hpp
lib/reopen.hpp
lib/crypt.hpp


I have a problem. Imagine a few of my files use lib/crypt.hpp. For example in app/file.hpp I should write:



#include "../lib/crypt.hpp"


If I take this file to lib folder it does not work anymore. So I need a something like:



#include "LIB/crypt.hpp"


So, this LIB/ has meaning of (empty) in lib directory while it has meaning of "../lib/" in app directory.


Then I will have no worry about moving file.hpp from app to lib. I just need to fix the callers of it. But not what it calls.


Similar to concept of web programming frameworks. Is it possible in C/C++?


How to use SFINAE on three methods with Intel C++ Compiler (ICC)?

I'm trying to add support for icc on one of my projects, but I have some issues with SFINAE, when there are more than two methods. Here is a bare simple example of the problem:



#include <iostream>

template<std::size_t Selector>
struct impl {
template<bool Enable = true, typename std::enable_if<Selector == 1 && Enable, int>::type = 0>
static void apply(){
std::cout << "First selector" << std::endl;
}

template<bool Enable = true, typename std::enable_if<Selector == 2 && Enable, int>::type = 0>
static void apply(){
std::cout << "Second selector" << std::endl;
}

template<bool Enable = true, typename std::enable_if<Selector == 3 && Enable, int>::type = 0>
static void apply(){
std::cout << "Big selector" << std::endl;
}
};

int main(){
impl<1>::apply();
impl<2>::apply();
impl<3>::apply();

return 0;
}


This works like a charm with g++ and clang++, but fails to compile with icc:



test.cpp(16): error: invalid redeclaration of member function template "void impl<Selector>::apply() [with Selector=1UL]" (declared at line 11)
static void apply(){
^
detected during instantiation of class "impl<Selector> [with Selector=1UL]" at line 22

test.cpp(11): error: invalid redeclaration of member function template "void impl<Selector>::apply() [with Selector=3UL]" (declared at line 6)
static void apply(){
^
detected during instantiation of class "impl<Selector> [with Selector=3UL]" at line 24

compilation aborted for test.cpp (code 2)


Is there a workaround for this with icc ?


Thanks


lundi 30 mars 2015

C++ metaprogramming assign unique ID to tree structures

I have an odd problem. I have a metaprogramming type defined like so:



template <int N, typename... Args>
struct mytype {
...
};


By default, I create them like this:



using type = mytype<-1, mytype<-1, mytype<-1, ...>>>;


Later on, I need to recurse through the type and recursively set each number to a unique ID. The IDs need to be sequential and start at 0 for long technical reasons. For instance, if I had this:



mytype<-1
mytype<-1, a, b>
>


I want it to become something like this:



mytype<0,
mytype<1, a, b>
>


It doesn't matter the order for the numbers' assignment.


I don't quite know how to approach this problem and have tried several things that didn't get anywhere. Any help would be greatly appreciated.


OpenFrameworks Doesn't Compile with c++11, GPGS needs c++11

I'm working on a game that is built using OpenFrameworks.


In it's make files, there is a -nostdlib CFLAG.


I'm trying to integrate Google Play Game Services' c++ sdk


I've copied the GPGS include & libs folder into my "libs project", and added the .a file to OF's PROJECT_STATIC_LIBRARY and the include folder to OF's header search paths.


Now, when I compile the project without adding -std=c++11 to the CFLAGS, I see 2 major errors in gpg.h: 'chrono' in namespace 'std' does not name a type and 'function' in namespace 'std' does not name a type.


But when I add -std=c++11 to CFLAGS, I see 3 major errors in OF code, all stemming from the use of 'dynamic_cast_tag". I've added a picture of ofTypes.h, (from open frameworks), where the error is.


enter image description here


while loop and getchar()

I have the simple program below that I wrote for a college course. I know it doesn't really do anything, but it's just an assignment for a course.


The part that I can't figure out, is why doesn't the outer loop work?


The user needs to press '1' to continue, and any other key the program exits.


However, it still doesn't continue if the user presses '1' and instead exits anyway.


I tried adding a cin.clear() before cin >> repeat, but that doesn't work.


I also tried playing around with cin.ignore(), but that didn't seem to help either.


Any ideas?


Thanks



int main()
{
int repeat = '1';
stack<char> cstr;
char c;

while (repeat == '1')
{
cout << "Enter in a name: ";

while (cin.get(c) && c != '\n')
{
cstr.push(c);
}

cout << "\n Enter another name? 1 = Continue, any other key to exit the program";
cin >> repeat;
repeat = getchar();
}
}

How to solve the array initialization issue with visual studio 2013

I want to declare an array as one of the members of the Struct. It fails, the compiler throws the following error:



error C2536: ... : cannot specify explicit initializer for arrays


Here is my struct in .h file:



struct CommandRepo
{
std::string root_command[5] = { "create", "edit", "remove", "list", "setting" };
std::string Base = "^(create|edit|remove|settings|list)(?: *)(?:--([a-zA-Z]*))";
std::string EachWord = "(\\w+)";
};


It seems (as read somewhere in SO), VSC2013 is not fully compliant with C++11, and the error is associated with that lack of compliance. Is that true? How should I solve it?


C++ Primer (5th Edition) and C++14

I've recently bought the book "C++ Primer (5th Edition) " and I've noticed that the book is updated to the C++11 version and not to the latest C++14. Is there anything that I need to do different to adapt myself to the new C++14?


I'm afraid that I'll learn things in the book that are no longer relevant, or not in the most efficient way, because of the differences between the versions and the additions to the C++14. If you could let me know if there is anything that I need to do differently to make my code more aesthetic or efficient, I would appreciate it.


c++ - incomplete type / forward declaration

This question has been asked many times but usually it could be easily solved by changing order of classes. In my case it may be not.



class GCRefLink;
class GCRef;

class GCRefLink {
friend class GCRef;
private:
GCRef * ref;
GCRefLink(GCRef * ref) : ref(ref) {}
public:
~GCRefLink(){this->ref->unlink();}
};

class GCRef {
friend class GCRefLink;
private:
int refCount;

GCRef() : refCount(0) {}
virtual ~GCRef(){}

void unlink(){--this->refCount;if(this->refCount==0) delete this;}
public:
GCRefLink link(){++this->refCount;return GCRefLink(this);}
};


When I change order of classes I'm getting the same error just about second class. It's meant to be reference class to inherit by managed, undeleteable classes, I know there's already such a thing in stl but as it's university project I need to implement my own.


I'm getting invalid use of incomplete type 'class GCRef' or invalid use of incomplete type 'class GCRefLink' errors


How to set compiling flags in cpp files (C++)

Thank you for reading my question, I searched everywhere on the net and i couldn't find an answer. I have a test (Olympiad in informatic) next week, The programming language that i'll be using is c++,My code gets compiled by a server which then respond weather my answer was true or false (Wrong compilation is considered as false of course), The problem is that i don't have an access to the compilation phase so i can not set c++ to be compiled as c++11 (Can't set compilation flags). My question is: Is there is any way i can add flags inside my cpp file (which will be uploaded to the server) to enable the c++11? Can it be done with predecessor with #somthing ? Note: I have no access except to the cpp file, NO makefile,nor anything else. Thank you For your help, i really apreciate it.


std::regex_error exception thrown at runtime (Not G++, but VS 2015)

guys!


I have this chunk of code:



// chunk 2
regex r{ R"(\d{2,3}(-\d\d) { 2 })" };
smatch matches;
if (regex_match("tel:223-45-67"s, r))
cout << matches[0] << endl;


But 1st line throws the std::regex_error exception. I know g++ doesn't support regex yet, but I think that brand new VS 2015 (CTP 15) should. I have this code working:



// chunk 2
regex r1{ "fish"s };
smatch m1;
if (regex_search("I love fish and chips"s, m1, r1))
cout << m1[0] << endl;


So I decided that VS2015 supports regular expressions.


What's wrong with 1st chunk?


Thank you!


Declaring An Instance Of A Class With Member Initializers In Another Class

So I have a class whose contructor contains member initializers like so:



class aClass
{

public:

//Functions
aClass(int sVal1, float sVal2, float sVal3,float sVal4); //Constructor
~aClass(); //Destructor
};


The constructor looking like this in the .cpp file of the class:



NPC::NPC(int sVal1, float sVal2, float sVal3, float sVal4)
:someValue(sVal1), sSomeValue(sVal2), tSomeValue(sVal3), fSomeVlaue(sVal4)
{

}


My question is: if I were to declare an instance of this class in another class header file as a private variable, what would the syntax of declaration be?


Varying case-insensitive string comparisons performance

So, my phd project relies on a piece of software I've been building for nearly 3 years. It runs, its stable (It doesn't crash or throw exceptions) and I'm playing with the release version of it. And I've come to realise that there is a huge performance hit, because I'm relying too much on boost::iequals. I know, there's a lot of on SO about this, this is not a question on how to do it, but rather why is this happening. Consider the following:



#include <string.h>
#include <string>
#include <boost/algorithm/string.hpp>

void posix_str ( )
{
std::string s1 = "Alexander";
std::string s2 = "Pericles";
std::cout << "POSIX strcasecmp: " << strcasecmp( s1.c_str(), s2.c_str() ) << std::endl;
}

void boost_str ( )
{
std::string s1 = "Alexander";
std::string s2 = "Pericles";
std::cout << "boost::iequals: " << boost::iequals( s1, s2 ) << std::endl;
}

int main ( )
{
posix_str();
boost_str();
return 0;
}


I put this through valgrind and cachegrind, and to my suprise, boost is 4 times slower than the native posix or the std (which appears to be using the same posix) methods. Four times, now that is a lot, even considering that C++ offers a nice safety net. Why is that? I would really like other people to run this, and explain to me, what makes such a performance hit. Is it all the allocations (seems to be from the caller map). I'm not dissing on boost, I love it and use it everywhere and anywhere.


c++ comparing all elements of a vector

I'm trying to create a C++ function which controls if N rectangles are collisioning. The N rectangles are in a std::vector. The idea is to compare every element of the vector with others (only one time) to verify if there are collisions. I already implemented code to do this, but I am looking for a better, cleaner and more elegant way (I'm a C++ newbie). My code is:



bool areCollisioningNRectangles(std::vector<Rectangle> rect) {
const unsigned long size = rect.size();

for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (areCollisioningTwoRectangles(rect[i], rect[j])) {
return true;
}
}
return false;
}
}

C++11 Initialization of template class member in template class

I have a bunch of template classes, based on an enumeration type. Here is the source code:



#include <iostream>

// An enum type
enum class ENUMR : unsigned char {
SYSTEM1,
SYSTEM2,
UNKNOWN
};

// template class; will later be specialized based on ENUMR enumerators
template<ENUMR S>
class System
{};

// specialized System class, for enumerator SYSTEM1
template<>
class System<ENUMR::SYSTEM1>
{
private:
static constexpr char identifier { 'G' };
};

// An observation class recorded from a certain System instance
template<ENUMR Sys,short int Freq>
class Obs {
public:
Obs():
m_system {System<Sys> {} }, // does not work
m_frequency {Freq}
{};
//{
// m_system = System<Sys> {}; // works
//}
private:
System<Sys> m_system;
short int m_frequency;
};

// dummy code to test the template classes
int main ()
{

System<ENUMR::SYSTEM1> s1;

System<ENUMR::UNKNOWN> s2;

System<ENUMR::SYSTEM1> s3 (System<ENUMR::SYSTEM1>);

Obs<ENUMR::SYSTEM1, 1> obs;

std::cout <<"\n";
return 0;
}


Initialization of the member (template) variable Obs::m_system produces a compile-time error, when performed as m_system {System<Sys> {} }. However, when the same variable is initialized as m_system = System<Sys> {}; the source codes gets compiled (the respective lines in the source code above are commented). Does that mean that the assignment operator works, but the copy constructor fails? If so, why? When compiled against the gcc version 4.8.3 i get the following error message:



test.cpp: In instantiation of ‘Obs<Sys, Freq>::Obs() [with ENUMR Sys = (ENUMR)0u; short int Freq = 1]’:
test.cpp:43:28: required from here
test.cpp:25:22: error: too many initializers for ‘System<(ENUMR)0u>’
m_frequency {Freq} {};

Objects created at the same time - unwanted compiler optimization?

I've got a weird problem:



for (size_t i=0; i<20; i++)
{
// pre is a vector<UserType>
pre.push_back(UserType()); // In UserType constructor, record std::chrono::steady_clock::now()
}


gives the following objects



(gdb) print pre $1 = std::vector of length 20, capacity 32 = {{timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}, {timePoint_ = {__d = { __r = 1427724945979761000}}}, {timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}, {timePoint_ = {__d = { __r = 1427724945979761000}}}, {timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}, {timePoint_ = {__d = { __r = 1427724945979761000}}}, {timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}, {timePoint_ = {__d = { __r = 1427724945979761000}}}, {timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}, {timePoint_ = {__d = { __r = 1427724945979761000}}}, {timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}, {timePoint_ = {__d = { __r = 1427724945979761000}}}, {timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}}



1, Theoretically, each of the 20 UserType objects should have different & unique time_since_epoch().count(), but in the gdb outputs, they're all the same.


2, I tried the same code here: http://ift.tt/1bJo30l and each object has a unique time stamp. So I'm observing different behaviours.


3, Some analysis: UserType() in pre.push_back(UserType()); is an rvalue; the compiler then value-copies(via copy constructor) the rvalue into an lvalue object in the vector pre. Is it possible that the compiler sees the constant loop number 20 and the rvalue object instructions, therefore decides to create 20 object "at the same time" as an optimization? Even if this is the case, it's not likely that the compiler can do construction all at the same time - there's no such thing as the same time - only small differences that can be ignored. I don't think the compiler can do 20 object constructions within 1 single tick of steady_clock.


4, Here's the relevant compilation flags in my Makefile - note that I did NOT ask the compiler to optimize: -g -Wall -std=gnu++0x


5, This piece of code(loop of 20 object constructions) was in a google test file; My compiler is g++ 4.8.3 on cygwin.


My questions is:


What is going on here? Specifically, why am I seeing the same time stamps for constructing the 20 objects?


Thanks a lot.


opencv linking error macosx 'undefined reference for architecture'

I am currently trying to compile a working camera calibration using g++4.9 and OpenCV 3.0 beta.


The Problem is I am getting some strange linking errors although I have linked everything like I linked it on my Ubuntu Machine.


This is the makefile I am using at the moment: CC=g++-4.9 CFLAGS=-c -g -fPIC -Wall -std=c++11 -fdiagnostics-color=auto



SRC=fisheye.cpp
OBJ=fisheye.o
PROG=fisheye

INC_PATH=-I/usr/local/include/opencv2/
LIB_PATH=-L/usr/local/lib/
LIBS= -lopencv_core \
-lopencv_highgui \
-lopencv_calib3d \
-lopencv_features2d \
-lopencv_imgproc

all: $(OBJ)
@$(CC) $(CFLAGS) $(INC_PATH) $(SRC) -o $(OBJ)
@echo 'Compiled fisheye.cpp successfully'
@$(CC) $(OBJ) -o $(PROG) $(LIB_PATH) $(LIBS)
@echo 'Linking complete'

clean:
rm -rf $(OBJ) $(PROG)


Which is just returning stuff like:



Compiled fisheye.cpp successfully
Undefined symbols for architecture x86_64:
"cv::imread(cv::String const&, int)", referenced from:
_main in fisheye.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
make: *** [all] Error 1


I built OpenCV manually using cmake and make and the directories are right. Compiling works the main Problem is the linking process.


If I compile and link using the following commands(where g++11 is an alias for g++-4.9 -std=c++11 -fdiagnostics-color=auto it fails with the same error:



//compiling:
g++11 -c -g -Wall -I/usr/local/include/opencv2/ fisheye.cpp

//linking:
g++11 -o fisheye fisheye.o -L/usr/local/lib/ -lopencv_core -lopencv_highgui -lopencv_calib3d -lopencv_imgproc -lopencv_features2d


I also took a look to similar topic on stack overflow but none of them fixed my problem.


Maybe anyone of you has an idea.


Why is std::seed_seq non-copyable according to C++11, and why doesn't gcc/clang conform?

Consider the following minimal example:



// main.cpp
#include <random>

int main(int, char **)
{
std::seed_seq seed1{1337, 42};
std::seed_seq seed2(seed1);
std::seed_seq seed3 = seed2;
return 0;
}


According to the C++ standard, this shouldn't compile, as std::seed_seq is neither copy constructible, nor copy assignable.


However, this compiles fine with both g++ 4.9, and clang 3.4



g++-4.9 -std=c++11 -Wall main.cpp
clang++ -std=c++11 -Wall main.cpp


The android ndk's llvm-libc++ implementation seems to follow the "not copyable" property of seed_seq. Which can be confirmed in the source at



android-ndk-r10d/sources/cxx-stl/llvm-libc++/libcxx/include/random:3553


Or by compiling the minimal example using



${NDK_HOME}/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/bin/arm-linux-androideabi-g++ \
-std=c++11 -c -Wall \
-I${NDK_HOME}/sources/cxx-stl/llvm-libc++/libcxx/include \
-I${NDK_HOME}/sources/cxx-stl/llvm-libc++/../llvm-libc++abi/libcxxabi/include \
-I/opt/android-ndk-r10d/sources/cxx-stl/llvm-libc++/../../android/support/include \
-isystem ${NDK_HOME}/platforms/android-18/arch-arm/usr/include \
main.cpp




I've previously used this (without being aware of my non-conforming code) to store a copy of the seed for logging purposes.*


I'm left wondering:




  1. Why it is that seed_seq isn't copyable?




  2. This is the first time I've encountered g++ and clang to not conform to the standard. Is it a conscious decision to deviate from the standard, or is this an implementation bug? How prevalent is this? I'd like to learn more.






* I realized that I was thinking of seed_seq wrong, and that if I'm only interested in the seed_seq::param values (the seed_seeq's initial seed values), that I should instead keep my copy in a vector<T>, instead of a type that is meant to generate integers.


is there a way to set the length of a std::string without modifying the buffer content?

According to the statements made in the answers of these questions



.. in C++-11 it should be possible to call a C API function which takes a char pointer to store the output like this:



str::string str;
str.reserve(SOME_MAX_VALUE);
some_C_API_func(&str[0]);


But is there now a legal way to set the size of the string to the length of the (null terminated) content inside the buffer? S.th. like this:



std.set_size(strlen(&str[0]));


This is a very unesthetic abuse of std::string anyway I hear you say but I can't create a temporary char buffer on stack so I would have to create a buffer in heap and destroy it afterwards (which I want to avoid).


Is there a nice way to do this? Maybe not reserving but resizing and calling erase() afterwards would do it but it doesn't feel nice neighter..


Expression involving function type is lvalue or rvalue?


void fn() {}
void (&lref)() = fn;
void (&&rref)() = fn;

int main() {}


Compiles well under g++ 4.8.1.


So, fn is an expression, and an expression must have a category according to the ISO standard. Which category then the expression belongs before any automatic type promotion since both references can accept the result of evaluating the expression fn?


define enum class with same name compared to enum

Why this compiles in c++11:



struct foo
{
enum class Resolution { None=10, Nominal=20 };
enum class Scale { None, Nominal };
};


while this doesn't:



struct foo
{
enum Resolution { None=10, Nominal=20 };
enum Scale { None, Nominal };
};


?


Can't compile C++ program on Ubuntu

I used OSX to program in C++, but I am new to C++ compiler on Linux. I have a program consisting two .cpp files and one .h file that are compiled and run successfully on my Mac, but get compiling errors on Ubuntu. I did install gcc and g++ compilers and build-essential, and also apt-get update and update, searched online, but in no vain. Does my Ubuntu lack of some library packages or some extra configuration needed to fix the problem?


Here is my program's compiling errors on Ubuntu:



WordCombine.cpp: In function ‘int BuildTrie(const string&, Trie*&, std::vector<std::basic_string<char> >&)’:
WordCombine.cpp:21:37: error: no matching function for call to ‘std::basic_ifstream<char>::basic_ifstream(const string&, const openmode&)’
ifstream ifs(filename, ifstream::in);
^
WordCombine.cpp:21:37: note: candidates are:
In file included from WordCombine.cpp:10:0:
/usr/include/c++/4.8/fstream:467:7: note: std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
basic_ifstream(const char* __s, ios_base::openmode __mode = ios_base::in)
^
/usr/include/c++/4.8/fstream:467:7: note: no known conversion for argument 1 from ‘const string {aka const std::basic_string<char>}’ to ‘const char*’
/usr/include/c++/4.8/fstream:453:7: note: std::basic_ifstream<_CharT, _Traits>::basic_ifstream() [with _CharT = char; _Traits = std::char_traits<char>]
basic_ifstream() : __istream_type(), _M_filebuf()
^
/usr/include/c++/4.8/fstream:453:7: note: candidate expects 0 arguments, 2 provided
/usr/include/c++/4.8/fstream:427:11: note: std::basic_ifstream<char>::basic_ifstream(const std::basic_ifstream<char>&)
class basic_ifstream : public basic_istream<_CharT, _Traits>
^
/usr/include/c++/4.8/fstream:427:11: note: candidate expects 1 argument, 2 provided


Here is my g++ -v info:



Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.8/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.8.2-19ubuntu1' --with-bugurl=file:///usr/share/doc/gcc-4.8/README.Bugs --enable-languages=c,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.8 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.8 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --disable-libmudflap --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-4.8-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-4.8-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-4.8-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1)