mercredi 27 décembre 2017

C++: Order of evaluation between cout and a function call

I went through few questions about std::cout evaluation order and I understand that there is no sequence point between the args of std::cout, however I am unable to understand how the following code works:

saved_fd = dup(STDOUT_FILENO);
std::cout << "Redirecting std out to /dev/null";
redirect_stdout()
<do some stuff>
std::cout << "Restoring std out back to standard output";
restore_stdout();

My functions redirect_stdout() and restore_stdout(), using the dup2 calls redirects standard output to /dev/null and restores it back later. I expect the only output to show up on screen is "Redirecting std out to /dev/null". But what I see is "Restoring std out back to standard output".

It appears that redirect_stdout() is getting run before its previous statement.

Just for completeness, here are the definitions of the two methods:

void redirect_stdout()
{
  dump_fd = open("/dev/null", O_RDWR, 0777);
  dup2(dump_fd, STDOUT_FILENO);
  cout << endl;
}

void restore_stdout()
{
  dup2(saved_fd, STDOUT_FILENO);
  cout << endl;
}

Why don't I see the first cout output?

String concatenation with user input in C++

I tried to write a code which gets an input from the user and concatenate with another string but it doesn't work well. The code is down below,

#include<iostream>
using namespace std;
int main() {
    string s1="Hi ";
    string s2;
    cin>>s2;
    s1=s1+s2
    cout<<s1;
    return 0;
}

Input: this is how it works

Expected Output: Hi this is how it works

But it didn't work as I expected.

The output of my code: Hi this

Can anybody help me?

Using =default in meaning of =delete

The followin code is well compiled:

struct B { 
    B(int) {} 
};

struct D : B {
    D() = default;
};

Until I have to create an instance of class D:

D d; // error: use of deleted function 'D::D()'

Is there any reason (use case) to allow = default for D's constructor, when it's actually works as = delete;?

How can I make a C++ member function by binding the arguments of another member function?

I am having problems with creating a variable of pointer-to-member-function (PTMF) type "on the fly" (that is, by pinning some arguments of an existing member function via std::bind). My question is if it is ever possible with C++11 or post-C++11 standard.

Preambula: I have a class that stores a static const array of std::functions initialized from PTMFs, hereinafter referred to as "handlers". Originally, they were regular member functions with a name and implementation so I didn't ever use C++11 and std::function. Then, I decided that many of them are nearly similar, and decided to generate them with a "generator function". I would like to avoid using templates for the generation because the number of these nearly similar handlers is going to dramatically increase in future (around 200+) and templatizing will just lead to code bloat.

If the PTMFs in question were static, I would have no problems with generating the handlers via std::bind. A simplified example:

#include <iostream>
#include <functional>


using namespace std;


struct A {
    typedef function<void(int)> HandlerFn;

    static void parametrized_handler(int i, const char *param) {
        cout << "parametrized handler: " << param << endl;
    }

    static void handler(int i) { cout << "handler 1" << endl; }

    int mm;
};

static const A::HandlerFn handler2 = [](int) { cout << "handler 2" << endl; };

static const A::HandlerFn handler3 = bind(A::parametrized_handler,
                                          placeholders::_1,
                                          "test_param");


int main()
{
    A::handler(42);
    handler2(42);
    handler3(42);

    return 0;
}

Output:

$ ./a.out 
handler 1
handler 2
parametrized handler: test_param

The problem arises when I turn to non-static member functions. std::bind is not able to generate a function object that acts like a PTMF. I know that I can pass a real object as a first argument to bind and get a working function but that is not what I want: when I am initializing a static const array, there are no objects at all, and the result of bind will act as a regular non-member function anyway.

An expected implementation for non-static member functions (with an imaginary std::bind_mem binder):

#include <iostream>
#include <functional>


using namespace std;

struct A;


struct A {
    typedef function<void(int)> HandlerFn;

    void parametrized_handler(int i, const char *param) {
        mm;
        cout << "parametrized handler: " << param << endl;
    }

    void handler(int i) const { mm; cout << "handler 1" << endl; }

    const HandlerFn handler2 = [this](int i) { mm; cout << "handler 2" << endl; };

    int mm;
};


// An imaginary PTMF binder
// static const A::HandlerFn handler3 = bind_mem(A::parametrized_handler,
//                                               placeholders::_1,
//                                               "test_param");



int main()
{
    A a;

    (a.handler)(42);
    (a.handler2)(42);
    //(a.handler3)(42);

    return 0;
}

Output:

$ ./a.out 
handler 1
handler 2

So is there a way to implement a PTMF argument binding?

cmake couln't generate build files when visual studio 15 2017 Win64 is specified

This may seem lame but my CMakeList.txt could not generate build files when "Visual studio 15 2017 Win64" is specified while "Visual studio 14 2015 Win64"!

I've visual studio 2017 community installed. Also, here is how my CMakeList.txt looks:

{

# Specify the minimum version for CMake
cmake_minimum_required(VERSION 2.8)

# Enable C++11 standard
set(CMAKE_CXX_STANDARD 11)  

#set variables
#$CMAKE_SOURCE_DIR:= 
set( ENV{CMAKE_SOURCE_DIR} D:/fake/path)

# Project's name
project(integrated)

# Set the output folder where your program will be created
set(CMAKE_BINARY_DIR ${CMAKE_BINARY_DIR}/bin)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})
set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR})

# The following folder will be included
include_directories("${PROJECT_SOURCE_DIR}/inc")

# get all *.cpp files recursively
file(GLOB_RECURSE SRC_FILES ${PROJECT_SOURCE_DIR}/*.cpp ${PROJECT_SOURCE_DIR}/*.hpp ${PROJECT_SOURCE_DIR}/*.h)
message("Files to compile: " ${SRC})
#disable if binary isn't required as output
#add_executable(integrated ${SRC_FILES})

#to make cmake generate a static library
add_library (integrated-static-lib STATIC ${SRC_FILES})

}

Any help comment please?!

c++ std async : almost no effect to spawn over several cores

This question is related to:

c++ std::async : faster on 4 cores compared to 8 cores

In the previous question, I was wondering why some code would run faster on 4 cores rather than 8 (answer: my cpu had 4 cores and 8 threads)

Now I am discovering that code is even faster on a single core.

I am on ubuntu 16.06. c++11. Intel® Core™ i7-8550U CPU @ 1.80GHz × 8

Here code for benchmarking computation time against number of core used

#include <math.h>
#include <future>
#include <ctime>
#include <vector>
#include <iostream>

#define NB_JOBS 2000.0
#define MAX_CORES 8

// no special meaning to this function, 
// just uses some CPU
static bool _expensive(int nb_jobs){
  for(int job=0;job<nb_jobs;job++){
    float x = 0.6;
    bool b = true;
    double f = 1;
    for(int i=0;i<1000;i++){
      if(!b) f=-1;
      for(double j=1;j<2.0;j+=0.01) x+= f* pow(1.0/sin(x),j);
      b = !b;
    }
  }
  return true;
}

static double _duration(int nb_cores){

  std::clock_t begin = clock();

  int nb_jobs_per_core = rint ( NB_JOBS / (float)nb_cores );

  std::vector < std::future<bool> > futures;
  for(int i=0;i<nb_cores;i++){
    futures.push_back( std::async(std::launch::async,_expensive,nb_jobs_per_core));
  }
  for (auto &e: futures) {
    bool foo = e.get();
  }

  std::clock_t end = clock();

  double duration = double(end - begin) / CLOCKS_PER_SEC;
  return duration;

}


int main(){

  for(int nb_cores=1 ; nb_cores<=MAX_CORES ; nb_cores++){

    double duration = _duration(nb_cores);
    std::cout << nb_cores << ": " << duration << "\n";

  }

  return 0;

}

Here the output:

1: 8.55817
2: 8.76621
3: 7.90191
4: 8.4656
5: 10.5494
6: 11.6175
7: 21.697
8: 24.3621

using cores seems to have marginal impacts. Note: "htop" shows usage of virtual cores as expected by the program, i.e. first one core used at 100%, then 2, ..., and at the end 8.

If I replace:

futures.push_back( std::async(std::launch::async,[...]

by :

futures.push_back( std::async(std::launch::async|std::launch::deferred,[...]

then I get:

1: 8.6459
2: 8.69905
3: 10.7763
4: 11.4505
5: 11.8426
6: 10.4282
7: 9.55181
8: 9.05565

and htop shows only 1 virtual core being used 100% during the full duration.

Anything I am doing wrong ?

note: I tried on several desktops, all with various specs (nb of core and nb of threads), and observed something similar.

template for new cmake c++ project: compiler option

I start new cross-platform c++ project and want to find good template, like autotools hello world.

I want:

  1. Check if compiler supports c++11
  2. If c++ comipler is clang or gcc then enable as much as possible warnings like -Wall, -Wextra and so on
  3. precompile headers support, and some file(s) to which I will add new headers for precompilation
  4. Simple way to enable/disable sanitizers
  5. Simple way to enable/disable code coverage gathering
  6. Simple way to enable/disable clang static analyzer

Can you point or give such cmake template for new project?