jeudi 30 juin 2016

how can i resolve Hackerrank "terminated for timeout"?

the question is to find no of reversible no.s below the following test cases and here reversible no.s means like 36 + 63 = 99 (contains both odd digit). both 36 and 63 are reversible . and we have to find total reversible no.s below a number.

i have also declared functions as inline , but it is still giving timeout error . for test case#1 to test case#5

inline std::string IntToString ( int number )
    {
      std::ostringstream oss;
       oss<< number;
      return oss.str();
    }


inline int replacer (int n)

{
int r,R=0;

while(n!=0)
    {
       r=n%10 ;
    R=R*10+r ;
     n=n/10;
}

return R ;

}




int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */   

int i,n,t,j,R,Q,L,k,d=0,M=0,D; 


cin>>t ; 

for(i=0;i<t;i++ )
    {
    M=0;
    cin>>n ;

    for(j=1;j<n;j++)
        {


        if(j%10!=0)
       { d=0;
        R= replacer(j) ;

       Q=R+j ;
        std::string C = IntToString (Q);

        L=C.size() ;  


        for(k=0;k<L;k++)
           if(C[k]%2==0)
            d=1 ;
           if(d==0) 
          M++ ;
       }    
    }
    cout<<M<<endl ;
    }


return 0;
}

How to pass a stack matrix by reference in C++

My question is simple, if I have a matrix created on the stack rather than on the heap, such as int matrix[10][10], how can I pass it by reference? Or, pass it in a way that it doesn't pass the whole matrix as argument, but just its pointer or reference, or whatever. I use C++11.

void proc(/*WHAT GOES HERE?*/ matrix, int n){    
    matrix[n-1][n-1] = 7;     
}

int main(){

    int matrix[10][10];     

    proc(matrix, 10);       

    return 0;

}

how can I copy vector in c++ by refference?

I want to have class scope allice to the vector from an argument.

For exapmale:

class Solution {
public:
     vector<int> a;
     int maxCoins(vector<int>& _a) {
          // here I want to do smth like a = _a; which works for O(1)
     }
};

Unfortunatelly, I can't just declare vector<int> &a; , because of the error: declaration of reference variable 'a' requires an initializer

Could you please, explain how to do it in C++11/14?

C++11 vector insert causes invalid access

I'm writing a DLL for some features and seeing a strange problem. If I use the below code in my DLL and try to load it, it throws the error:

// Sample code
uint8_t data[SIZE_MAX]; // SIZE_MAX = 15
std::vector<uint8_t> v(data, data + SIZE_MAX);
// more code
std::vector<uint8_t> appendData; // initialize it with some value
v.insert(v.end(), appendData.begin(), appendData.end());

ERROR:
LoadLibraryW failed with error (3E6): Invalid access to memory location.

I have been using the same code for a while and it always worked. However, it stopped working suddenly and I'm not sure what exactly is causing this error. Any pointers?

Object declaration with preceding :: in C++ [duplicate]

This question already has an answer here:

What does following represent in C++?

::SomeNameSpace::SomeClass abc;

Basically how is this different from

SomeNameSpace::SomeClass abc;

How to combine operator << with the comma operator to assign multiple values to an array or vector class member?

I would like to overload operator << combined with the comma operator in order to provide a way of assigning multiple comma-separated values to a std::array or std::vector class member.

For example, given the following class declaration:

class MyClass{
public:
   A() {}
   ~A() {} 
private:
   std::array<double, 5> a_{};
}

I would like to be able to use the following syntax:

MyClass m;
m << 9, 10, 11, 99, 5;

Which in turn would update a_ by setting the corresponding values (9 at a_[0], 10 at a_[1] and so on). Operator << should also raise an error if the number of comma-separated values does not match std::array::size

Thanks for any advice on how to proceed!

Here strcmp() don't work. why?

I just compared with string a and b. But why did I get compiler error ? Have any limitation here to compare with string by strcmp() ?

#include <bits/stdc++.h>

using namespace std;
int main()
{
    int n;
    string ar,a,b;
    while(scanf("%d",&n) != EOF){
        if(n == 0) break;
        for(int i = 0; i < n; i++){
            cin>>ar[i];
        }
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                a = ar[i] + ar[j];
                b = ar[j] + ar[i];
            }
            if(strcmp(a,b) < 0){
                swap(a,b);
            }
        }
        cout<<a[0];
        printf("\n");
    }
    return 0;
}

C++ Segmentation Fault Passing Class Variables to Class Functions

So I'm trying to have a class variable that is a vector and pass it in between some class functions. A basic version of what I'm trying to do is captured in the following:

#include <iostream>
#include <string>
#include<stdlib.h>
#include <vector>
using namespace std;


class isingModel {
    private:
        int length;

    public:
        void set_values (int);
        void ising_Iterator(vector<vector<int> > & );
        vector<vector<int> >  lattice;
};


void isingModel::set_values (int l) {
    length = l;
    vector<vector<int> > lattice(length, vector<int>(length));

    for (int i=0;i<length;i++){
        for (int j=0;j<length;j++){
                int randNum = rand() % 2; // Generate a random number either 0 or 1
                lattice[i][j]=2*(randNum-.5); //shift value so that it is either 1 or -1.
        }
    }
}

void isingModel::ising_Iterator (vector<vector<int> > & lattice) {

    lattice[0][0]=1;

}



int main () {
    int L;
    cout << "Enter the length of the lattice: ";
    cin >> L;

    isingModel iModel;

    iModel.set_values(L);
    iModel.ising_Iterator(iModel.lattice );
    return 0;
}

So I have a class that has some functions, but my main goal is to make a class variable vector and then pass it to different class functions. In this code I make vector called lattice and set it's values in set_values and then after passing lattice to ising_Iterator by reference and want to change some values in lattice. According to the documentation and other questions I thought I would have to pass the vector by reference (hence the & in the function declaration). But I seem to still getting segmentation fault. I used gdb to discover that the problem is in ising_Iterator, so it must be that the class function ising_Iterator does not have access to the lattice vector. One of the reasons I'm so confused is that if I replace

void isingModel::ising_Iterator (vector<vector<int> > & lattice) {

    lattice[0][0]=1;

}

with

void isingModel::ising_Iterator (vector<vector<int> > & lattice) {

    length=1;

}

everything compiles and runs fine. So I've concluded that passing class variables that are vectors to class functions and changing them is fundamentally different then just passing class variables to class function and changing them there..

How to control compiler flag invoked when specifing CMAKE_CXX_STANDARD?

I would like to have cmake manage the inclusion of the "-std=c++14" compiler flag. This is easy to do using the CMAKE_CXX_STANDARD as described here. This boils down to including the following:

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED on)

However, when using gcc, this results in the inclusion of "-std=gnu++14" which includes some non-standard features. Is there a way to have cmake invoke the "-std=c++14" compiler flag when using CMAKE_CXX_STANDARD instead of "-std=gnu++14"?

error: ‘NOEXCEPT’ does not name a type | error: expected initializer before ‘_NOEXCEPT’

I am trying to compile C++ a file on my RaspberryPi (Linux) but it is throwing an error of :

error: expected initializer before ‘_NOEXCEPT’ JSONException JSONException::MissingKey(const std::string &key) _NOEXCEPT ^ /root/libapiai_demo/libapiai/apiai/src/exceptions/JSONException.cpp:23:101: error: expected initializer before ‘_NOEXCEPT’ JSONException JSONException::TypeMismatch(const std::string &key, const std::string &expected_type) _NOEXCEPT

I even tried to replace it with throw() and _GLIBCXX_USE_NOEXCEPT but that didn't work.

On replacing it with noexcept (small) It throws an error of:

error: declaration of ‘ai::Exception::Exception(const char*) noexcept’ has >a different exception specifier Exception::Exception(const char *reason) noexcept: reason(reason) {

Is it a problem with my compiler but I am using a latest one.

My CMake txt file also has :

include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
        message(FATAL_ERROR "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()

add_compile_options(-std=c++11)

For code to compile, still it throws errors.

g++ --version g++ (Raspbian 4.9.2-10) 4.9.2

Below is the 1 such file which throws the error.

Is it like 4.9.2 doesn't support noexcept. Can someone help me with this since I am stuck.

#ifndef EXCEPTION_H
#define EXCEPTION_H

#include <string>
#include <exception>

namespace ai {

class Exception: public std::exception
{
private:
    std::string reason;
public:

    Exception(const char *reason) _NOEXCEPT;

    virtual const char* what() const _NOEXCEPT override;

    virtual ~Exception() _NOEXCEPT;
};

}
#endif // EXCEPTION_H

Nicer syntax for setting default argument value to default constructor

One might want to declare a function with an argument, and specify that the default value for the argument is the result of the type's default constructor:

void foo(a::really::long::type::name arg = a::really::long::type::name());

Is there a nicer syntax for this that doesn't involve entering the type name twice? Something like:

void foo(a::really::long::type::name arg = default);

I realize I can typedef the type name to make it prettier, but I'm curious whether such a syntax exists.

C++ if/else statement problems

I was using xcode the other day, and was working on a text-based conversation game-thingy.

#include <iostream>

int main()
{
    std::cout<<"Conversation simulator requires you to type in all caps for all  of your replies"<<std::endl;
    std::cout<<"Type your first and last name!"<<std::endl;
    std::string fname = " ";
    std::string lname = " ";
    bool samename = false;
    std::cin>> fname >> lname ;
    if  (fname == "MUSCLE" and lname == "MAN")
        std::cout<< "Wow, we have the same first and last name!"<<std::endl;
        samename = true;
    else
        std::cout<< fname << " "<< lname << "is a very nice name"<<std::endl;

return 0;
}

nothing seems quite wrong to me, but Xcode won't run because on this line:

else

it expected an expression? I can't think of what that might mean.

Error C1001 on Visual Studio 2015 with std::enable_if

I have some C++11 code that fails to compile on Visual Studio 2015 (Update 2), but compiles without error on both Clang and GCC. Therefore, I am suspecting a compiler bug in Visual Studio, but maybe my code is somehow ill-formed.

My real class BaseUnit is a template wrapper class over a double value, taking care about the physical dimensions of quantities (expressed as SI units m, kg, s, K). For example, the multiplication of a Speed with a Time template instance automatically gives a Distance instance. The problem occurs with the current implementation of the multiplication with a scalar. I have simplified the class as much as I could to show the problem.

#include <type_traits>

template<int M>
class BaseUnit
{
public:
    constexpr explicit BaseUnit(double aValue) : value(aValue) {}
    template<typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0>
        BaseUnit operator*(U scalar) const { return BaseUnit(value * scalar); }
    template<typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0>
        friend BaseUnit operator* (U scalar, BaseUnit v) { return BaseUnit(scalar*v.value); }
protected:
    double value;
};

int main()
{
    BaseUnit<1> a(100);
    a = 10 * a;  // <-- error C1001 here
    return 0;
}

When compiling on Visual Studio, whatever the command line options, an internal error C1001 appears:

C:\temp>cl bug.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23918 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

bug.cpp
bug.cpp(19): fatal error C1001: An internal error has occurred in the compiler.
(compiler file 'msc1.cpp', line 1433)
 To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++
 Help menu, or open the Technical Support help file for more information
Internal Compiler Error in C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe.  You will be prompted to send an error report to Microsoft later.
INTERNAL COMPILER ERROR in 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe'
    Please choose the Technical Support command on the Visual C++
    Help menu, or open the Technical Support help file for more information

From some experiments, it happens that both operator* definitions are needed for the error to appear. If either the prefix or the postfix version is removed, the sample code can compile fine.

I may fill out a bug report on Microsoft if this behavior is confirmed to be a bug, and not already a well-known issue of the compiler.

Counting elements in a list with different objects given a property

So i got this two classes and i want to count the number of FlowersGarden objects with the specie rose in my list:

class Garden {
private:
    string owner;
    double lenght, width;
public:
    Garden(string ow, double l, double w) {
        this->ownder = ow;
        this->lenght = l;
        this->width = w;
}

class FlowersGarden: public Garden {
private:
    string species;
public:
    FlowersGarden(string ow, double l, double w, string sp):Garden(ow, l, w) {
        this->species = sp;
}
    string GetSpecie()const {return species;};
};

main.cpp

Graden** list;
list = new Garden* [5];
list[0] = new Garden("asdas", 54, 57);
list[1] = new FlowersGarden("tyyty", 98, 87, "rose");
list[2] = new FlowersGarden("asdasd", 578, 212, "sadas");
list[3] = new Garden("uyiyui", 687, 212); 
int count = 0;
for (int i = 0; i < 4; i++)
    if(dynamic_cast<FlowersGarden*>(list[i]))
        if(list[i]->GetSpecies() == "rose")
           count++;

That's only i can think of solving this problem and i'm getting this error: "class 'Garden' has no member named 'GetSpecies'" and i see why, but i don't know another way.

Quickly converting a string in the format of '0 1 1 0 1' into a bitset

How can I quickly convert a string of ones and zeroes separated by spaces into a bitset?

There exists a constructor to initialize a bitset from a string not separated by spaces, one to initialize a bitset to all zeroes or ones, and one to initialize from an integer. Off the top of my head, I can think of three ways:

  • Removing the spaces from the string and passing it to the constructor
  • Converting the binary into an integer and passing it to the constructor
  • Initializing all values to zero and changing the value of each bit according to the string in a for-loop

The number of bits is 24, and each string has exactly 24 bits, no more, no less.

QUiLoader widget not showing if loaded in derived QWidget

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    QVBoxLayout *vLayout = new QVBoxLayout(this);

    QUiLoader loader;

    QFile file("untitled.ui");
    file.open(QFile::ReadOnly);
    QWidget *w = loader.load(&file);
//    MyWidget *w = new MyWidget(loader.load(&file));
    vLayout->addWidget(w);
    file.close();

    QPushButton *btB = new QPushButton;
    vLayout->addWidget(btB);
}

enter image description here

The code above produces the image above. But I would like to do something with the widget just loaded, that's why I derived MyWidget from QWidget. And there seems to be the problem.

If I replace QWidget by MyWidget then it doesn't show there anymore. The code below produces the image below.

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    QVBoxLayout *vLayout = new QVBoxLayout(this);

    QUiLoader loader;

    QFile file("untitled.ui");
    file.open(QFile::ReadOnly);
//    QWidget *w = loader.load(&file);
    MyWidget *w = new MyWidget(loader.load(&file));
    vLayout->addWidget(w);
    file.close();

    QPushButton *btB = new QPushButton;
    vLayout->addWidget(btB);
}

enter image description here

Where mywidget.h:

#include <QWidget>

class MyWidget : public QWidget
{
    Q_OBJECT
public:
    explicit MyWidget(QWidget *parent = 0);

signals:

public slots:

};

And mywidget.cpp:

#include "mywidget.h"

#include <QDebug>
MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent)
{
    qDebug() << "do something here";
}

Why the widget (group box) isn't showing there? How to make it appear?

Threads in a vector can't be joined

I want to store a collection of threads in a vector, and join them all before exiting my program. I receive the following error when trying to join the first thread no matter how many I place in the collection:

system_error: thread::join failed: No such process

Here is some simple code that demonstrates my issue:

#include <thread>
#include <iostream>
#include <vector>
#include <functional>

using std::cout;
using std::endl;
using std::vector;
using std::thread;
using std::mem_fn;

int main()
{
  vector<thread> threads(1);
  threads.push_back(thread([]{ cout << "Hello" << endl; }));
  for_each(threads.begin(), threads.end(), mem_fn(&thread::join));

  // also tried --> for(thread &t : threads) t.join()
}

And I'm building it using the following (tried clang++ 4.2.1 and g++ 5.3.1):

g++ -o src/thread_test.o -c -std=c++14 src/thread_test.cpp
g++ -o thread_test src/thread_test.o -lpthread

I see lots of examples doing just this around the internet. Did something change in the contract of <thread> or <vector> that's rendered these examples defunct?

Is it legal to initialize a thread_local variable in the destructor of a global variable?

This program:

#include <iostream>

struct Foo {
    Foo() {
        std::cout << "Foo()\n";
    }

    ~Foo() {
        std::cout << "~Foo()\n";
    }
};

struct Bar {
    Bar() {
        std::cout << "Bar()\n";
    }

    ~Bar() {
        std::cout << "~Bar()\n";
        thread_local Foo foo;
    }
};

Bar bar;

int main() {
    return 0;
}

Prints

Bar()
~Bar()
Foo()

for me (GCC 6.1, Linux, x86-64). ~Foo() is never called. Is that the expected behaviour?

Operator.() in C++17 [duplicate]

This question already has an answer here:

I am not sure if this is the type of question that should be asked on Stack Overflow but I was wondering how and when one can tell if operator dot is going to be included in C++17? I read that the meeting in which this decision was going to be made would be towards the end of June of 2016 (http://ift.tt/1Rnu5AU)

I am getting slightly impatient as I personally do not want it to be included in the standard :(

std::map crash after erase when used on different calls

I have a simple TCP server socket handler which uses std::map to store the list of socketID and their associate server class pointer. I made this to have single handler to handle multiple servers.

Whenever I create a server socket, I add the socket ID and the respective server class pointer to the map list.

int c_socketInterface::openTCPServerConnection( char *ptrIPAddr, unsigned short port){
int nSocket = (socketDescriptor)socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

printf("Opening TCP-Server connection at: %s:%d on Socket :%d", ptrIPAddr, port, nSocket);

if (-1 != nSocket) {
    struct sockaddr_in stSockAddr;
    memset(&(stSockAddr), '\0', sizeof(sockaddr_in));
    stSockAddr.sin_family = AF_INET;
    stSockAddr.sin_port = htons(port);
    stSockAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    int nOptVal = 1;
    if (setsockopt(nSocket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *)&nOptVal, sizeof(nOptVal)) == -1) {
        if (0 == bind(nSocket, (struct sockaddr *) &stSockAddr, sizeof(struct sockaddr))) {
            if (-1 == listen(nSocket, 5)){
                printf("socketInterface: listen() failed: %ld\n", WSAGetLastError());
            }
        }
    }
}

return nSocket;

}

  1. After opening server connection, the listening socket ID is added to the map
  2. Once the client connects to the server, the accepted socket ID is also added to the same map list.(Hope listening socketId and acceptConnection socketId are not same)
  3. When the client sends some data, it is received on the accept connection socketId.
  4. When the client closes the socket, it is notified to the server via the accept connection socket.
  5. During this stage, the accept connection socket Id should be erased from the std::map list and the socket handler should continue to look for other any data on other sockets.

My std::map

typedef std::map<int, serverClass *> sockConnectionContainer;
sockConnectionContainer sockConnectionList;

Removing and Adding to the list:

void c_socketHandler::addCallbackFunc(int sockDesc, serverClass  *pa_poServer) {

sockConnectionList.insert(make_pair(sockDesc, pa_poServer));
isConnectionListChanged = true;

if (!isAlive()){
    this->start("Socket Handler"); //Start socket handler thread
}
resumeSelfSuspend();
}

void c_socketHandler::removeCallbackFunc(socketDescriptor sockDesc) {

for (sockConnectionContainer::iterator iter = sockConnectionList.begin(); iter != sockConnectionList.end(); ) {
    if (iter->first == sockDesc) {
        iter = sockConnectionList.erase(iter);
    }
    else {
        ++iter;
    }
}

isConnectionListChanged = true;
}

creating FDset:

int c_socketHandler::createFDSet(fd_set *fdSet) {
    intretVal = ZERO_VALUE;
    FD_ZERO(fdSet);

for (sockConnectionContainer::iterator iter = sockConnectionList.begin(); iter != sockConnectionList.end(); ++iter) {
    FD_SET(iter->first, fdSet);
    if(iter->first > retVal){
        retVal = iter->first;
    }
}

isConnectionListChanged = false;
return retVal;
}

socket handler thread:

void c_socketHandler::run(void) {
struct timeval tv;
fd_set anFDSet;
fd_set anFDSetMaster;

int nHighestFDID = 0;
int retval = 0;

FD_ZERO(&anFDSetMaster);

while (isAlive()){

    if (sockConnectionList.empty()){
        selfSuspend();
    }

    if (true == isConnectionListChanged){
        nHighestFDID = createFDSet(&anFDSetMaster);
    }
    anFDSet = anFDSetMaster;


    tv.tv_sec = 1; 
    tv.tv_usec = 1001;

    if (0 != nHighestFDID){
        retval = select(nHighestFDID + 1, &anFDSet, NULL, NULL, &tv);
    }

    if (retval > 0){

        for (sockConnectionContainer::iterator iter = sockConnectionList.begin(); iter != sockConnectionList.end(); ++iter) {
            serverClass *serverClassPtr = iter->second;
            int sockDesc = iter->first;

            if ((0 != FD_ISSET(sockDesc, &anFDSet)) && (0 != serverClassPtr)) {
                serverClassPtr->recvData(&sockDesc, 0)) {
            }
        }
    }
}
}

Issue here is the accept connection socketId sometimes stored as a last element and while erasing using the removeCallback function the iter points the end of the map. But when the function call gets completed, the iterator inside the socket handler thread run() gives an exception when doing ++iter.

how to solve this issue? Also I need to know should I need to remove the listening socket ID or the accept connection socket ID. In case, the client may connect again anytime. I didn't face any exception when closing the listening socket ID as the socket ID was lesser than the accept connection ID, so practically seeing it is not the end of the map.

Parent issue (?) while using derived Qt widget class

The following is the smallest example I could make to present the isuue.

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    QVBoxLayout *vLayout = new QVBoxLayout(this);

    QGroupBox *gb = new QGroupBox;
//    MyGroupBox *gb = new MyGroupBox;
    vLayout->addWidget(gb);

    QPushButton *btB = new QPushButton;
    vLayout->addWidget(btB);
}

enter image description here

The code above produces the image above, it's just a group box and a button in vertical layout.

If I replace QGropBox by MyGroupBox then it doesn't show there anymore. The code below produces the image below.

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    QVBoxLayout *vLayout = new QVBoxLayout(this);

//    QGroupBox *gb = new QGroupBox;
    MyGroupBox *gb = new MyGroupBox;
    vLayout->addWidget(gb);

    QPushButton *btB = new QPushButton;
    vLayout->addWidget(btB);
}

enter image description here

Where mygroupbox.h:

#include <QWidget>

class MyGroupBox : public QWidget
{
    Q_OBJECT
public:
    explicit MyGroupBox(QWidget *parent = 0);

signals:

public slots:

};

Why the group box isn't showing there? How to make it appear?

const qualifier to decltype

My first try of using decltype

vector<int> vals;
const decltype(&vals[0]) ptr;

for (const auto& val : vals)
    ptr = &val;    

doesn't compile, complaining about assigning to read-only variable ptr. What I'm trying to achieve is ptr to be of type const int*. How can I make it work? Thanks.

placement new for lambda capture

I have an interesting problem with C++ lambdas. The use case is a performance-critical thread that constructs a lambda with non-empty closure which is then passed to a different thread so it can be "worked" on.

The overall idea works but my lambda closure object gets copied one extra time and compiler (currently g++ 5.4.0) is not able to optimize away this copy including with copy elision. I also tried clang with similar outcome.

Ideally I would like to use a placement new when creating lambda objects directly in the durable memory instead of first creating object on stack for example:

auto l = new (buf) [a,b,c](){}

The error is something like:

lambda_ctor.cpp:39:19: error: expected type-specifier before '[' token
    auto al = (buf) new [a,b,c](){};

I was thinking maybe if I had a type in hand instead of actual lambda expression compiler should accept it but trying to lift type of closure without evaluating it runs into another problem:

using T = decltype([a,b,c](){});

with this error:

lambda_ctor.cpp:41:24: error: lambda-expression in unevaluated context
    using T = decltype([a,b,c](){});

I can't seem to find a way around this, there are a number of ideas on how to keep lambda from disintegrating on scope exit but every solution seems to involve copying/moving the closure object once it has been created (aka extra copy). This is a little strange because normally we have full control over how a user-defined functor is created and passed around and similar rules should apply to closures.

For loop alters values not specified in the loop declaration at every iteration

I have a tree structure in my program, in which each object contains a list of pointers to its children in a vector.

int main(int argc, char* argv[]){
    ...
    Compartment* head = readIn(argc, argv, count);

Where readIn(int,char*,int) reads in data from an outside file and creates the tree based on that:

Compartment* readIn(int argc, char* argv[], int &count){
    ...
    Compartment* head = nullptr;
    ... //reads in data
    if (parID == -1){
        Compartment* c = new Compartment(params...,nullptr); //head so no parent
        head = c;
    } else {
        Compartment* c = new Compartment(params...,Compartment::fndID(parID,head));
    }
    ...
    return head;
}

Where fndID(int,Compartment*) is a recursive DFS that returns a pointer to the Compartment with the specified ID, and the Compartment constructor uses push_back() to add the constructed object to its parents list of children.

I then construct a 2D matrix on the heap, and start a for loop that (non-destructively) deals with the tree. However, on the second iteration of the loop, I get a segfault! Upon investigating, I found that the vector of children of the head Compartment had become truncated, but that it had happened from the front! I was missing the first two values of the vector, leaving only the second two. However, when I checked the values immediately before the end of the first iteration of the for loop, the whole vector is there, so something must be happening at the end. My first thought is that I'm doing pointers wrong, but if so, how? Or is it something else entirely?

Casting an alias template to the aliased type

Consider this code:

struct foo {/* stuff */};

template <typename T>
using bar = foo;

// Elsewhere
bar<int> A;
auto &B = static_cast<foo&>(A);

Is using B legal?

Using constexpr together with getenv (or alternative)

I'm trying to capture environment variables from a build server as compile time constants that can be used within the build library. I have a static class that can be queried for these constants and would like to use constexpr with std::getenv, but I get the errors that constexpr variable must be initialised from a constant expression due to the fact that getenv returns a non-const char*, due to the fact it is a little long in the tooth.

I'd like to avoid bloating the build scripts by injecting all of the env vars as -DMY_ENV_VAR if possible. If the answer is simply "no, you must add each as a definition like that", and there are no modern alternatives to getenv or tricks I can use then so be it, but then there are 2 spots to maintain, which is not ideal.

C++ 11: Storing a pointer to object returned with NRVO

If I write a factory method that instantiates an object locally and then returns by value, intending to take advantage of NRVO (as per some of the answers here: c++11 Return value optimization or move?), will a pointer/reference to the local object point to the object that is assigned the return value of the method?

Object ObjectBuilder::BuildObject( void )
{
    Object obj;

    this->ObjectReference = obj;
    //OR
    this->ObjectPtr = &obj;

    return obj;
}

In use:

ObjectBuilder builder;

Object newObject = builder.BuildObject();

Does builder.ObjectPtr refer to newObject?

std::regex with another Allocator

I'm stuck how to use the regex_match template with my own Memory STL Allocator.

This is my code:

FaF::smatch stringResults;
std::regex expression( "expression" );
std::regex_match( std::string-variable, stringResults, expression );

For std::match I was successful and therefore I use it in the above example:

namespace FaF
{
    using smatch = std::match_results<std::string::const_iterator,
                                          Allocator<std::string::const_iterator>>;
}

My Allocator has some logging and I can see clearly, yes it is indeed used. When I understand the cppreference correctly, then std::regex does not have an allocator, but std::regex_match does.

My question:

How to define - according the above types - in the namespace FaF an additional template based on std::regex_match which is using my STL Memory Allocator?

Should STL map::insert support move semantics with move_iterators?

I have a large amount of data to load into a map from file, which is already in sorted order (because it was serialized from the map). I've discovered it is faster to first load the data into a vector, and then bulk-load into a map with insert. This saves just over a second in a 19sec load time.

The value_type is a structure that contains vectors of other structures. I don't need the vector after the load completes, so I use move_iterators in my call to map::insert. Using MSVC 2015 (VC14), the data isn't moved into the map, but instead is copied via const_reference deep inside the STL code.

Is this a standard-compliant implementation, to ignore the moving of data?

template<typename Stream, typename Key, typename Type, typename Traits, typename Allocator>
bool const read(Stream &is, std::map<Key, Type, Traits, Allocator> &map)
{
    size_t size;
    read(is, size);

    std::vector<std::pair<Key, Type>> items(size);
    for (size_t i=0; i<size; ++i)
    {
        auto &item = items[i];
        if (!read(is, item.first)  ||  !read(is, item.second))
            return false;
    }
    map.insert(std::make_move_iterator(items.begin()), std::make_move_iterator(items.end()));

    return !!is;
}

I've overcome the problem replacing the map.insert with

for (auto &item : items)
    map.insert(std::move(item));

but it isn't so neat, but does save another 0.6 seconds.

Lambda function capture by copy results in corruped data

std::vector<Spell*> playerSpells{ new Jump(1), new Arrow() };

for each (auto spell in playerSpells)
{
    spell->icon->onClickEndEH.add([=]() {
        auto a = spell;
        auto b = spell->sprite;
    });

    player->addSpell(spell);
}

First, I checkedspell variable before the add function and it's fields are initialized correctly. When the lambda function is called, the variable b is corrupted. I can provide other parts of the code if that's not enough.

Android app runs on Cortex A9 processor but not on Cortex A7

My Android app, which uses a C++ library built using the NDK, runs on a Nexus 7 (Android 4.3, processor = ARM Cortex A9), and on another tablet using Android 6.1, but fails on two other devices using the ARM Cortex A7 processor.

One of the failing devices is a mobile phone running Android 5.1 (symptom of failure = black screen on startup, and no subsequent progress).

The other failing device is a development board (http://ift.tt/296sN1I), on which the symptom of failure is the normal 'unfortunately app has stopped' message.

I don't think the problem is lack of RAM in the case of the development board; it has 1GB of RAM, which is the same as that of the Nexus 7.

The C++ library is built using C++11: the android.mk file includes the lines

LOCAL_CPP_FEATURES=exceptions
LOCAL_CPPFLAGS += -std=c++11

and the application.mk file is

APP_ABI := armeabi x86
APP_STL := c++_static

I can't find any reference to this problem anywhere on the web.

C++11: Why result_of can accept functor type as lvalue_reference, but not function type as lvalue_reference?

I've got program below:

#include<type_traits>
#include<iostream>
using namespace std;
template <class F, class R = typename result_of<F()>::type>
R call(F& f) { return f(); }

struct S {
    double operator()(){return 0.0;}
};
int f(){return 1;}
int main()
{
    S obj;
    call(obj);//ok
    call(f);//error!
    return 0;
}

It fails to compile in the line of "call(f)". It's weird that "call(obj)" is OK.

(1) I've a similar post in another thread C++11 result_of deducing my function type failed. But it doesn't tell why functor objects are OK while functions are not.

(2) I'm not sure if this is related to "R call(F& f)": a function type cannot declare a l-value?

(3) As long as I know, any token with a name, like variable/function, should be considered a l-value. And in the case of function parameter, compiler should "decay" my function name "f" to a function pointer, right?

(4) This is like decaying an array and pass it to a function----And a function pointer could be an l-value, then what's wrong with "call(F& f)"?

Would you help to give some further explanations on "why" is my case, where did I get wrong? Thanks.

Forcing operator_ (underscore)

This question is for fun, I know that I cannot define operator_.

However, I'd really like to "bend" this rule, having something like the following as valid (with valid being loosely defined!).

T result = somevar _ someother;

I didn't come with a possible solution, but maybe you can, possibly using some preprocessor übertricks. (Of course just #define _ SOMETHING is quite a bit dangerous)

Any help is greatly appreciated!

Move into a function that takes const lvalue reference

I am using this class, not written by me and I can't change its code:

class A {
private:
    Val d_val;
public:
    void setVal(const Val& val) { d_val = val; }
    const Val& getVal() const { return d_val; }
};

Val supports move but class A was written without that in mind. Can I somehow avoid a copy of val in the scenario? I doubt std::move(val) into setVal will work since it doesn't take an r value reference.

A a;
Val val;
// populate val
a.setVal(val); // I don't need val after here

term doesnt evaluate to 1 argument in std algorithm when using unary op defined with std::unique_ptr

I am trying to use a std::unique_ptr functor in std algorithm but if i use it like -

std::unique_ptr<IFormatter> format(new formatter("abcd"));
std::transform(vec.begin(), vec.end(), vec.begin(), format.get()) 

i am getting compilation error saying - "Error 1 error C2064: term does not evaluate to a function taking 1 arguments."

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


    struct IFormatter
    {
    protected:
    std::string keyFormat;
    void fun(std::string& str)
    {
        // do something here.
    }
public:
    IFormatter(std::string keyFormat) : keyFormat(keyFormat)
    {}
    virtual std::string operator() (const std::string &key) = 0;
};
struct formatter : IFormatter
{
    formatter(std::string keyFormat) : IFormatter(keyFormat)
    {}
    std::string operator() (const std::string &key)
    {
            std::string s = keyFormat;
            fun(s);
            return s;
    }
};

int main()
{        
    std::vector<std::string> vec{ "one", "two" };
    std::unique_ptr<IFormatter> format(new formatter("TRADE:INTRADAY:$ID$"));
    // This line compiles fine if i define format as - formatter format("abcd");
    std::transform(vec.begin(), vec.end(), vec.begin(), format.get());
    start s;
    return 0;
}

Bad allocation error when my_list.push_back()

I am trying to control de workflow of a program I am developing. To do so I have a map< unsigned int, list < unsigned int > > in which the first key will be the id and the second ( the list ) will be used to know if I end correctly all tasks. The only operations I use on this list are:

myMap[iD].size()
myMap[iD].push_back(foo) <- ( foo is an unsigned int )
for (std::list<unsigned int>::iterator it=myMap[iD].begin(); it != myMap[iD].end(); ++it){
myMap[iD].erase(it)
}

The length of my map can grow to 1452 elements and each element list size can be from the order of 1000 ~ 5000.

When I run the program sometimes I receive a segmentation fault and some times a bad allocation error. My guess is that this come from the push_back because:

  • If I don't push back any element the program works fine.
  • The storage for the new elements is allocated using the container's allocator, which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed). http://ift.tt/299Khe9

This is the only part of the code where I use the map:

if (FOO != 0){
    if (PID != 0){

        if ( myMap.size() + 5 < myMap.size().max_size()){
            if (myMap.size()[PID].size() > 1000) myMap.size()[PID].pop_front();
            myMap.size()[PID].push_back(EVENTVALUE);
        }

    }
} else {
    if (PID != 0 and foo2 != 0 and myMap.size().find(PID) != myMap.size().end()) {
        for (std::list<unsigned int>::iterator it=myMap.size()[PID].begin(); it != myMap.size()[PID].end(); ++it){
            if (*it == foo2){
                cout << " erasing pid: " << PID <<  endl;
                myMap.size()[PID].erase(it);
                if ( myMap.size()[PID].size() == 0 ) myMap.size().erase(PID);
                break;
            }

        }
    }
}

I've also tried to use the tool Valgrind and this is the output:

==4092== Invalid read of size 8
==4092==    at 0x4F09EB8: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) (in /usr/lib64/libstdc++.so.6.0.21)
==4092==    by 0x40CCA9: construct<std::basic_string<char>, const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&> (new_allocator.h:120)
==4092==    by 0x40CCA9: _S_construct<std::basic_string<char>, const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&> (alloc_traits.h:254)
==4092==    by 0x40CCA9: construct<std::basic_string<char>, const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&> (alloc_traits.h:393)
==4092==    by 0x40CCA9: std::vector<std::string, std::allocator<std::string> >::push_back(std::string const&) (stl_vector.h:905)
==4092==    by 0x4157AC: foo::foo(std::basic_ofstream<char, std::char_traits<char> >&) (foo.cc:1743)
==4092==    by 0x404F49: main (foo.cc:3159)
==4092==  Address 0x6157d08 is 0 bytes after a block of size 8 alloc'd
==4092==    at 0x4C29670: operator new(unsigned long) (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==4092==    by 0x40DB77: allocate (new_allocator.h:104)
==4092==    by 0x40DB77: _M_allocate (stl_vector.h:168)
==4092==    by 0x40DB77: void std::vector<std::string, std::allocator<std::string> >::_M_emplace_back_aux<std::string>(std::string&&) (vector.tcc:404)
==4092==    by 0x408F3E: push_back (stl_vector.h:920)
==4092==    by 0x408F3E: split(std::string const&, char, int) (foo.cc:416)
==4092==    by 0x41577F: lustreLine::toPRV(std::basic_ofstream<char, std::char_traits<char> >&) (foo.cc:1741)
==4092==    by 0x404F49: main (foo.cc:3159)
==4092== 
==4092== Invalid read of size 4
==4092==    at 0x4F09EBB: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) (in /usr/lib64/libstdc++.so.6.0.21)
==4092==    by 0x40CCA9: construct<std::basic_string<char>, const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&> (new_allocator.h:120)
==4092==    by 0x40CCA9: _S_construct<std::basic_string<char>, const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&> (alloc_traits.h:254)
==4092==    by 0x40CCA9: construct<std::basic_string<char>, const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&> (alloc_traits.h:393)
==4092==    by 0x40CCA9: std::vector<std::string, std::allocator<std::string> >::push_back(std::string const&) (stl_vector.h:905)
==4092==    by 0x4157AC: foo::foo(std::basic_ofstream<char, std::char_traits<char> >&) (foo.cc:1743)
==4092==    by 0x404F49: main (foo.cc:3159)
==4092==  Address 0xfffffffffffffff8 is not stack'd, malloc'd or (recently) free'd
==4092== 
==4092== 
==4092== Process terminating with default action of signal 11 (SIGSEGV)
==4092==  Access not within mapped region at address 0xFFFFFFFFFFFFFFF8
==4092==    at 0x4F09EBB: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) (in /usr/lib64/libstdc++.so.6.0.21)
==4092==    by 0x40CCA9: construct<std::basic_string<char>, const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&> (new_allocator.h:120)
==4092==    by 0x40CCA9: _S_construct<std::basic_string<char>, const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&> (alloc_traits.h:254)
==4092==    by 0x40CCA9: construct<std::basic_string<char>, const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&> (alloc_traits.h:393)
==4092==    by 0x40CCA9: std::vector<std::string, std::allocator<std::string> >::push_back(std::string const&) (stl_vector.h:905)
==4092==    by 0x4157AC: foo::foo(std::basic_ofstream<char, std::char_traits<char> >&) (fpp.cc:1743)
==4092==    by 0x404F49: main (foo.cc:3159)
==4092==  If you believe this happened as a result of a stack
==4092==  overflow in your program's main thread (unlikely but
==4092==  possible), you can try to increase the size of the
==4092==  main thread stack using the --main-stacksize= flag.
==4092==  The main thread stack size used in this run was 8388608.

[...]

( If more output is need just ask )

I've had to change some variable names for privacy, hope this is not a problem.

Thanks for reading and have a nice day!

mercredi 29 juin 2016

C++ Exceptions not allowed

Are there any reasons not to use C++ Exceptions with gcc?

Our company disallows them, but did not provide the reasoning behind the decision. Nobody of us "stupid people" can think of any reason why. Suggestions?

ODB: create a db success but db file no exist

I try to new a ODB dataBase, however, sometimes, if xxx.db is not exist even I new db success. With the code under, it cant catch exception however,it can enter if(!_file)

string dbFile = getPalBundle()->getFileStorageProvider()->getDocumentsPath(userId + "/xxx.db");

  auto db = std::shared_ptr<odb::sqlite::database>(new odb::sqlite::database(dbFile, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_SHAREDCACHE | SQLITE_OPEN_FULLMUTEX, false));


    if(db == nullptr)
    {
        ret = false;
    }

    // check database avalible
    try {
        db->schema_version();
    } catch (...) {
        DLOG(kTagDaoFactory, "Datase file damaged, logout");
        ret = false;
    }

    fstream _file;
    _file.open(dbFile, ios::in);
    if (!_file) {
        ret = false;
        DLOG(kTagDaoFactory, "Data base file no exist, logout");
    }

I have no idea what happens, could anyone help me? Thanks in advance!

std::initializer_list conversion in constructors

I'm new to C++11 and I was wondering how this code works internally:

class MyClass
{
    public:
        MyClass(int a, double b) {
            cout << "ctor()" << endl;
        }
};

int main()
{
    MyClass i1{4, 7};
    return 0;
}

My understanding of the new initializer list is that it is a class std::initializer_list constructed by special syntax { .... } in the code. So how does this class instance created by {4, 7} internally get transformed to a form that fits the constructor to MyClass? Thanks.

c++11 enable_if error - template parameter re-declaration

I am trying to get the following code to compile:

template <class T, typename std::enable_if<!std::is_fundamental<T>::value, int >::type = 0 >
class Calc
{
  public:
    int operator()( const T& v ) const {
        return v.getValue();
    }
};

template <class T, typename std::enable_if<std::is_fundamental<T>::value, int >::type = 0 >
class Calc : CalcBase <T>
{
};

On compilation I am getting the following error:

c.cpp:26: error: template parameter 'typename std::enable_if<(! std::is_fundamental::value), int>::type <anonymous>'
c.cpp:36: error: redeclared here as 'typename std::enable_if<std::is_fundamental::value, int>::type <anonymous>'

The intent here is to select the the version of Calc that overrides the base class function call operator if the passed template parameter is a class. If the passed parameter is a fundamental type, then we choose the version of Calc that does not override the base class functionality. Could you please help me understand how I can get this working?

In C++11 when should we explicitly use std::decay?

We know that compiler will decay array/function to pointers when needed(according to context), then when is the time we should explicitly use std::decay?

Is there any task that requires us to use it, or else, compiler doesn't know how to handle it?

Thanks.

How do I initialize a map with initializer list

I'm stuck with a map initialization problem. I want a table to access all the directions of my tetris blocks. I have tried a lot of methods to initialize it, but it seems too complex to be initialized.

This is the error info this time:

错误 C2440 “初始化”: 无法从“initializer list”转换为“std::map,std::allocator<_Ty>>,std::allocator>>>,std::less<_Kty>,std::allocator>,std::allocator>>>>>>” WinApp c:\codes\learning\winapp\tetris.cpp 44

I wonder how to initialize this table.

in my block class:

typedef std::map<shapes, std::vector < std::vector<std::pair<int, int> > > > proj;
static proj dirs ;

in the .cpp file:

block::proj block::dirs = 

{
{ 6,{ { TL, TC, MR },{ TC, ML, BL } } },
{ 4,{ { TR, TC, ML },{ TC, MR, BR } } },
{ 5,{ { ML, MR, BC },{ TC, MR, BC },{ TC, ML, MR },{ TC, ML, BC } } },
{ 3,{ { TL, TC, ML } } },
{ 2,{ { { ML, BL, MR },{ TC, BC, BR },{ TR, ML, MR },{ TL, TC, BC } } } },
{ 1,{ { ML, BR, MR },{ TR, TC, BC },{ TR, TC, BC },{ TL, MR, ML },{ TC, BC, BL } } },
{ 0,{ { ML, MR,{ 2,0 },{ TC, BC,{ 0,2 } } } } }  // sticks out
};

I defined the pairs as const vars for short.

const   std::pair<int, int>    TL{ -1,-1 };      /* top left */
const   std::pair<int, int>     TC{ 0,-1 };        /* top center */
const   std::pair<int, int> TR{ 1,-1 };     /* top right */
const   std::pair<int, int>  ML{ -1,0 };              /* middle left */
const   std::pair<int, int>  MR{ 1,0 };               /* middle right */
const   std::pair<int, int>    BL{ -1,1 };       /* bottom left */
const   std::pair<int, int>   BC{ 0,1 };         /* bottom center */
const   std::pair<int, int>     BR{ 1,1 };       /* bottom right */

Why atomic overloads for shared_ptr exist

Why are there are atomic overloads for shared_ptr as described here (http://ift.tt/1jrtS5s) rather than there being a specialization for std::atomic which deals with shared_ptrs. Seems inconsistent with the object oriented patterns employed by the rest of the C++ standard library..

And just to make sure I am getting this right, when using shared_ptrs to implement the read copy update idiom (http://ift.tt/1ltw7nl) we need to do all accesses (reads and writes) to shared pointers through these functions right?

Weird Linker errors in C++

These are the errors I'm getting

I honestly have no idea what these really means. Does it mean I typed in a character that isn't UTF? Just a bit confused.

This is libraryDriver.cpp

#include <iostream>
#include "Library.h"
#include "Book.h"
using namespace std;
int main()
{
    using namespace CS20A;
    Library l;
    l.addBookToCollection( "J. K. Rowlings", "Harry Potter and the Deathly Hallows" );
    l.addBookToCollection( "Barack Obama", "The Audacity of Hope" );
    l.addBookToCollection( "Vera Brittain", "Testament of Youth" );
    // Print out the library and its book
    cout << l << endl;
    try {
        l.checkoutBook( "Barack Obama", "The Audacity of Hope" );
        l.checkinBook( "Barack Obama", "The Audacity of Hope" );
        l.checkoutBook( "Vera Brittain", "Testament of Youth" );
    } catch( BookNotFound bnf ) {
        cout << "An error occurred here for the reason:";
        cout << bnf.what() << endl;
    }
    // Print out the library and its book - notice the difference
    cout << l << endl;
    // Let's try to throw some errors...
    try {
        // can't checkout a book not in the Library
        l.checkoutBook( "Barry Manilow", "Sweet Life : Adventures On The Way To Paradise" );
        cout << "An error occurred here..." ;
    } catch( BookNotFound bnf ) {
        bnf.what();
    }
    try {
        // can't checkout a book that is already being reserved
        l.checkoutBook( "Vera Brittain", "Testament of Youth" );
        cout << "An error occurred here..." ;
    } catch( BookNotFound bnf ) {
        bnf.what();
    }
}

Library.cpp

Thank you so so much. I went ahead and added things I believe where correct.

But I still get 2 more errors.

From what you've told me, I THINK that what the #3 error is saying is that inside Library.cpp, I'm referencing something in Book.h and so I have to include Book.h. I went ahead and did that but still got the error.

This is what my Library.cpp is now

#include "Library.h"
#include "Book.h"
#include <stdexcept>

using namespace std;
namespace CS20A{
    Library::Library(){
    }
    void Library::addBookToCollection(string author, string title){
        Book book(author,title);    
        myBooks[myNumberOfBooksSeenSoFar] = book;
        myNumberOfBooksSeenSoFar++;
    }
    void Library::checkoutBook(std:: string author, std:: string title) throw(...)
    {
        Book book(author, title);
        int booklocation;
        bool bookfound = false;

        for(int i = 0; i<myNumberOfBooksSeenSoFar; i++)
        {
            if(myBooks[i].getTitle() == book.getTitle() && myBooks[i].getAuthor() == book.getAuthor())
            {
                bookfound = true;
                booklocation = 1;
            }
        }
        if(!bookfound)
        {
            myBooks[booklocation].increaseNumberOfTimesCheckedOut();
        }
        else
        {
            throw BookNotFound();
        }
    }

    void Library::checkinBook(std::string author, std::string title) throw(...)
    {
        Book book(author, title);
        int booklocation;
        bool bookfound = false;

        for(int i = 0; i<myNumberOfBooksSeenSoFar; i++)
        {
            if(myBooks[i].getTitle() == book.getTitle() && myBooks[i].getAuthor() == book.getAuthor())
            {
                bookfound = true;
                booklocation = 1;
            }
        }
        if(bookfound)
        {

        }
        else
        {
            throw BookNotFound();
        }
    }
    ostream &operator<< (ostream& out, const Library & l)
    {
        for(int i = 0; i<l.myNumberOfBooksSeenSoFar; i++)
        {
            out << "Title: " << l.myBooks[i].getTitle() << endl << "Author: " << l.myBooks[i].getAuthor() << endl;
        }
        return out;
    }
}

Library.h

#ifndef LIBRARY_H
#define LIBRARY_H
#include <string>
#include "Book.h"
#include "BookNotFound.h"

using namespace std;
namespace CS20A
{
    class Library
    {
    public:
        Library();
        void addBookToCollection( string author, string title );
        void checkoutBook( string author, string title ) throw (BookNotFound);
        void checkinBook( string author, string title ) throw (BookNotFound);
        friend ostream& operator<< ( ostream& out, const Library & l );
    private:
        Book myBooks[ 20 ];
        int myNumberOfBooksSeenSoFar;
    };
}
#endif

Book.cpp

#include "Book.h"
#include <string>

using namespace std;
namespace CS20A {
    Book::Book(string author, string title) {
        my_Author = author;
        my_Title = title;
    }
    string Book::getTitle() const {
        return(my_Title);
    }
    string Book::getAuthor() const {
        return(my_Author);
    }
    int Book::getNumberOfTimesCheckedOut() const {
        return(my_NumberOfTimesCheckedOut);
    }
    void Book::increaseNumberOfTimesCheckedOut(int amount) {
        my_NumberOfTimesCheckedOut = my_NumberOfTimesCheckedOut + amount;
    }
    ostream &operator<< (ostream& out, const Book & b){
        out << "Title: " << b.my_Title << endl;
        out << "Author: " << b.my_Author << endl;
        out << "Number of time checkout out: " << b.my_NumberOfTimesCheckedOut;
        return(out);
    }
}

Book.h

#ifndef BOOK_H
#define BOOK_H
#include <string>
using namespace std;
namespace CS20A
{
    class Book {
    public:
        Book();
        Book( string author, string title );
        string getTitle() const;
        string getAuthor() const;
        int getNumberOfTimesCheckedOut() const;
        void increaseNumberOfTimesCheckedOut( int amount=1 );
        friend ostream& operator<< ( ostream& out, const Book & b );
    private:
        string my_Author;
        string my_Title;
        int my_NumberOfTimesCheckedOut;
    };
};
#endif

BookNotFound.h

#ifndef BOOKNOTFOUND_H
#define BOOKNOTFOUND_H
#include <stdexcept>
#include <iostream>
#include <string>

namespace CS20A
{
    class BookNotFound : public std::logic_error
    {
    public:
        BookNotFound():logic_error("Error"){};
        BookNotFound(std::string e):logic_error(e){};
    };
};
#endif

Using a std::promise with thread with member function error C2664

I am getting an error saying

error C2664: 'void std::_Pmf_wrap> &&),void,WalkingController,std::promise> &&>::operator ()(_Farg0 &,std::promise> &&) const' : cannot convert argument 2 from 'std::promise>' to 'std::promise> &&'

I am trying to create a promise that will run on a separate thread to execute a member function in my class. It looks like this:

std::promise<std::tuple<float, float>> p_upperTorques;
auto f_upperTorques = p_upperTorques.get_future();
std::thread t1(&WalkingController::CalculateTorqueForUpperLegs, this, std::move(p_upperTorques));
t1.join();
...std::get<0>(f_upperTorques.get()), std::get<1(f_upperTorques.get())...

The function I am calling is

void WalkingController::CalculateTorqueForUpperLegs(std::promise<std::tuple<float, float>> &&p) {
...
p.set_value(std::make_tuple(ullTorque, urlTorque));
}

Whats the correct way to do this?

Thanks for the help.

SWIG argument error when using "using std::vector" in python

This is very related to this question

Regardless of whether or not this is coding practice, I have come across code that looks like this

test.hh

#include <vector>                                                                                   
using std::vector;                                                             

class Test 
{                                                                     
    public:                                                                      
        vector<double> data;                                                     
};  

I am trying to swig this using swig3.0 using the following interface file

test.i

%module test_swig                                                                

%include "std_vector.i"                                                          

namespace std {                                                                  
    %template(VectorDouble) vector<double>;                                      
};                                                                               

%{                                                                               
    #include "test.hh"                                                               
%}                                                                               

%naturalvar Test::data;                                                                                 
%include "test.hh"    

And the following test code

test.py

t = test.Test()                                                              
jprint(t)                                                                    
a      = [1, 2, 3]                                                                
t.data = a # fails   

doing so gives me the following error

in method 'Test_data_set', argument 2 of type 'vector< double >'

This can be fixed by either changing the using std::vector in test.hh to using namespace std or by removing using std::vector and changing vector<double> to std::vector<double>. This is not what I want.

The problem is that I was given this code as is. I am not allowed to make changes, but I am supposed to still make everything available in python via SWIG. What's going on here?

Thanks in advance.

How do tbb threads consume the tasks?

Lets say I have a for loop of 1M iteration and I decide to use two threads. If I say grain size is 1B then tbb will create 1B tasks and roughly each thread gets 500 tasks.

The question is how do they split these tasks each other?

Is it like thread 1 get first 500 task and thread 2 gets last 500?

Or is it more like they go and pick a random task from the pool of 1B tasks?

Is there even any ordering in between tasks?

Is an empty constructor with initializer list considered trivial?

Is the following constructor considered trivial?

struct A
{
    A() : a(nullptr) {}
private:
    int* a;
};

These examples makes me a little confused. With c++11 this should also be possible:

struct A
{
private:
    int* a{nullptr};
};

and a should be properly initialized to nullptr. Here I did not define the constructor, but it should have the same form as the first implementation. Is either of these classes considered trivial?

The purpose of me asking is if I can expect move/copy constructors and assignment operators being automatically generated.

Do timed pointers exist?

In some cases I desired to have some kind of timed-based smart pointer, for example to cache some bulky object but release it automatically after a certain time if not used. When the pointer is touched (dereferenced) the count down is restarted, and you can also halt the count down if you need to 'lock' the object alive for duration of a computation. Something like:

timed_ptr<Type,30> p = new Type(); \\object is deleted after 30 seconds, and pointer set to a checkable 'null' state

...

p.stop_count_down();
// do something with the object, guaranteed it won't expire while we still need it. 
p.start_count_down();

Does anything of this sort exists in boost or other library?

Program crashes when trying to dereferrence a non null char*

I'm trying to read from the memory of a different process's module using ReadProcessMemory in the winapi:

BOOL WINAPI ReadProcessMemory(
  _In_  HANDLE  hProcess,
  _In_  LPCVOID lpBaseAddress,
  _Out_ LPVOID  lpBuffer,
  _In_  SIZE_T  nSize,
  _Out_ SIZE_T  *lpNumberOfBytesRead
);

The line causing my program to crash is: myfile << *buffer; and I know it's causing it because when I comment the line out my program works fine. Here are all lines that are relevant:

int inc = 0;
char* buffer = new char;
fstream myfile ("C:\\Users\\Edward Severinsen\\Desktop\\temp-memory.txt", ios::app);
if(!(myfile.is_open())){cout << "Unable to open file\n";system("pause");}

...

if(Module32First(snapshot, &modEntry) == FALSE){printf("Mod32First failed: %d", (int)GetLastError());CloseHandle(snapshot);return 1;}
while(ReadProcessMemory(proc, modEntry.modBaseAddr+inc, &buffer, sizeof(buffer), NULL) != 0)
{
if(buffer == nullptr)
        {
            cout << "buffer is a null pointer\n";
            system("pause");
            CloseHandle(snapshot);
            CloseHandle(proc);
            return 1;
        }
        printf("%c", buffer);
        myfile << *buffer;
        inc++;
    }

And even though I don't think it's necessary here's all the code in my program:

#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <fstream>
#include <iostream>
#define DWNULL 0xFFFFFFFF
using namespace std;

int main()
{
    DWORD pid = DWNULL;
    MODULEENTRY32 modEntry;
    int inc = 0;
    char* buffer = new char;
    fstream myfile ("C:\\Users\\Edward Severinsen\\Desktop\\temp-memory.txt", ios::app);
    if(!(myfile.is_open())){cout << "Unable to open file\n";system("pause");}

    modEntry.dwSize = sizeof(MODULEENTRY32);

    cout << "PID: " << flush;
    cin >> pid;

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
    if(snapshot == INVALID_HANDLE_VALUE){printf("Snapshot failed: %d", (int)GetLastError());CloseHandle(snapshot);return 1;}
    HANDLE proc = OpenProcess(PROCESS_VM_READ, FALSE, pid);
    if(proc == INVALID_HANDLE_VALUE){printf("Error: %d", (int)GetLastError());return 1;}
    if(Module32First(snapshot, &modEntry) == FALSE){printf("Mod32First failed: %d", (int)GetLastError());CloseHandle(snapshot);return 1;}

    while(ReadProcessMemory(proc, modEntry.modBaseAddr+inc, &buffer, sizeof(buffer), NULL) != 0)
    {
        if(buffer == nullptr)
        {
           cout << "buffer is a null pointer\n";
           system("pause");
           CloseHandle(snapshot);
           CloseHandle(proc);
           return 1;
        }
        printf("%c", buffer); //Prints first character then goes to next line and crashes.
        myfile << *buffer;
        inc++;
    }
    system("pause");
}

Why does age*12 produce a garbage value? [duplicate]

This question already has an answer here:

I'm just wondering why my code produces a garbage value.

#include "std_lib_facilities.h" // cool lib from bjarne.

int main()
{
    cout << "Please enter your first name and age (followed by pressing 'enter'\n";

    string first_name = "???";
    int age;
    int age_12 = age * 12;

    cin >> first_name >> age;
    cout << "Hello, " << first_name << " (months " << age_12 << ")!\n";

    return 0;
}

I know that you can do

cout << "Hello, " << first_name << " (months " << age * 12 << ")!\n";

Which solves the problem but I'm just interested in why it produces a garbage value.

Do C++11 threads provide a way for detached threads to continue after the main thread exits?

Normally, when main() exits, all threads are killed. pthread_exit(3) says

To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).

Is there an equivalent C++11 API call? Something like std::this_thread::exit(0)?

How to define signals with macros in Qt

I try to create a some standart signal definitionsfor some classes with macros like:

#define CREATE_SIGNALS void error_signal(QString error);

Functions are created, but moc did not create methods for these functions. It seems that moc is running before macros processed. How can i make this work?

Strange behavor of C++11 normal_distribution()

I have a problem, for some predefined stddev value random number generators d1 and d2 behave very differently.

 mt19937 generator;
 std::normal_distribution<long double> d1(0.0,stddev);
 std::normal_distribution<long double> d2(0.0,1.0);

 d1(generator);
 stddev*d2(generator);

I used this generators as part of a Monte Carlo simulation and expected to get similar results but this was not the case. I was wondering if someone also had similar experience.

Inheritance wrong call of constrostructors

I'm implemeting this diamond inheritance:

class Object {
private:
    int id; string name;
public:
    Object(){};
    Object(int i, string n){name = n; id = i;};
};



class Button: virtual public Object {
private: 
    string type1;
    int x_coord, y_coord;
public:
    Button():Object(){};
    Button(int i, string n, string ty, int x, int y):Object(i, n){
          type = ty;
          x_coord = x;
          y_coord = y;};
};


class Action: virtual public Object {
private:
    string type2;
public:
    Action():Object(){};
    Action(int i, string n, string t):Object(i, n){ type2 = t;};
};


class ActionButton: public Button, public Action{
private:
    bool active;
public:
    ActionButton():Buton(), Action(){};
    ActionButton(int i, string n, string t1, int x, int y, string t2, bool a):
    Button(i, n, t1, x, y), Action(i, n, t2) {active = a;};
};

Everything works fine about the first three classes, but when i try to create an object of the type ActionButton, instead of calling the constructor with the parameters i wrote it is calling the default one from the class Object. So every ButtonAction object has name an empty string and id a random value. What's wrong with my code and how can i make it work properly?

One template specialization for PODs, one for class hierarchy and error in other cases?

I'm trying to create a template which would work one way for all fundamental types, other way for all classes deriving from A and fail for everything else. Reading about SFINAE, I created such thing:

struct A {};
struct B : A
{
    int a;
};
template <typename T, typename = typename std::enable_if<std::is_base_of<A, T>::value>::type>
void foo(const T& derived)
{
    std::cout << "stuff with derived";
}

template <typename T, typename = typename std::enable_if<std::is_fundamental<T>::value>::type>
void foo(const T& pod)
{
    std::cout << "stuff with fundamental";
}

int main()
{
    foo(7);
    B instance;
    foo(instance);
}

From what I understood, matching template types for 7 (int) fails for first case and works for second, and derived class works for first. What mistake am I doing?

Using auto with initializer list

I have question regarding interaction between auto and initializer list. Example code:

#include <iostream>

int main()
{
auto a{ 1 };
auto b = { 1 };
auto c = 1;

std::cout << typeid(a).name() << std::endl;
std::cout << typeid(b).name() << std::endl;
std::cout << typeid(c).name() << std::endl;

return 0;
}

Gives output:

int
class std::initializer_list<int>
int

Which is kind of confusing. I'm posting this question as a followup to this. What should happen? I've did some research and it seems that auto c = 1; is illegal now, and it seems that it works because compilers allow this as a backwards compatibility patch. Does this apply also to auto a{1}?

C++ std::localtime daylight saving time rule (dst) european vs american

I've problem with use of the std::localtime function. When I transform a std::time_t to a local struct tm, it always use the american daylight saving time whereas I want to use the european one (France).

UTC : 03/19/16 16:56 is transformed in Local : 03/19/16 18:56.

At this date, normally, local is 17:56 (UTC+1). The DST happens on the 27th in France. After several tests, it seems that the used DST is based on the american rule : DST happens on second sunday in march.

I've also changed the TZ environement variable, but it also fails.


`

if( putenv( "TZ=CET-1CEST-2,M3.5.0/2,M10.5.0/3" ) != 0 ) { 
     std::cout << "Unable to set TZ" << std::endl; 
} else { 
   tz = getenv("TZ"); 
   if (tz) std::cout << tz << std::endl; 
   else std::cout << "TZ not defined" << std::endl; tzset(); 
}

struct std::tm t;
t.tm_sec = 0;
t.tm_min = 56;
t.tm_hour = 18;
t.tm_mday = 19;
t.tm_mon = 3-1;
t.tm_year = 2016-1900;
t.tm_isdst = -1;
std::time_t tt = std::mktime(&t);
std::cout << "UTC: " << std::put_time(std::gmtime(&tt), "%c %Z") << '\n'; // UTC : 03/19/16 16:56
std::cout << "local: " << std::put_time(std::localtime(&tt), "%c %Z") << '\n'; // Local : 03/19/16 18:56 (not waited result)

`

As a precision, I use the bcc32c compiler (the embarcadero C++ clang based computer).

I hope I'm clear enough and you'll be able to help me.

Thanks in advance

Why does the compiler complain about this not being a constexpr?

I am trying to learn a bit more about using constexpr in practice and created the following Matrix class template:

#include <array>
#include <vector>

template <typename T, int numrows, int numcols>
class Matrix{
public:
    using value_type = T;
    constexpr Matrix() : numrows_(numrows), numcols_(numcols){}
   ~Matrix(){}

    constexpr Matrix(const std::array<T, numrows*numcols>& a) :
        numrows_(numrows), numcols_(numcols),values_(a){}

    constexpr Matrix(const Matrix& other) :
        numrows_(other.numrows_), numcols_(other.numcols_), values_(other.values_){

    }

    constexpr const T& operator()(int row, int col) const {
        return values_[row*numcols_+col];
    }

    T& operator()(int row, int col){
        return values_[row*numcols_+col];
    }

    constexpr int rows() const {
        return numrows_;
    }

    constexpr int columns() const {
        return numcols_;
    }


private:
    int numrows_;
    int numcols_;
    std::array<T, numrows*numcols> values_{};
};

The idea is to have a simple Matrix class, which I can use for small matrices to evaluate Matrix expressions at compile time (note that that I have not yet added the usual Matrix operators such as additions and multiplication).

When I try to initialize a Matrix instance as follows:

constexpr std::array<double, 4> a = {1,1,1,1};
constexpr Matrix<double, 2, 2> m(a);

I am getting the following error from the compiler (MS Visual C++ 14):

error: C2127: 'm': illegal initialization of 'constexpr' entity with a non-constant expression

Note sure what I am doing wrong...any help to make this work would be greatly appreciated!

Container type of std::stack

I have questions about std::stack Why these two constructors are explicit ?

     explicit stack( const Container& cont = Container() );
     explicit stack( Container&& cont = Container() );

Note: Source

QKeyEvent isAutoRepeat not working?

So, I have an application where if a particular button is kept pressed it plays an audio device, when the button is released it stops the audio device. I use keyPressEvent and KeyReleaseEvent to implement this which is similar to the code below:

void ConsoleMainWindow::keyPressEvent(QKeyEvent *event)
{
    if(event->isAutoRepeat())
    {
        event->ignore();
    }
    else
    {
        if(event->key() == Qt::Key_0)
        {
            qDebug()<<"key_0 pressed"<<endl;
        }
        else
        {
            QWidget::keyPressEvent(event);
        }
    }
}

void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
    if(event->isAutoRepeat())
    {
        event->ignore();
    }
    else
    {
        if(event->key() == Qt::Key_0)
        {
            qDebug()<<"key_0 released"<<endl;
        }
        else
        {
            QWidget::keyReleaseEvent(event);
        }
    }
}

But apparently isAutoRepeat function isn't working as I can see continuous print out of key_0 pressed and key_0 released despite the fact I haven't released the 0 key after I have pressed it. Is my code wrong or something else is wrong?

Thanks.

Why does this function cause a crash if accessed via a pointer?

I have the following code:

void Aurora64::Messaging::SendConsoleMessageToPlayer(int channelId , const char *msg) 
{
    CGameRules *pGameRules = new CGameRules;
    pGameRules->SendTextMessage(eTextMessageConsole, msg, eRMI_ToClientChannel, channelId);
    delete(pGameRules);
}

It accesses a function in another class through pointer pGameRules, however the function causes the program to crash when it is called.

This code is inside the Aurora64 class in another file.


When placing the following code inside the pointer's class CGameRules (in a function that is executed inside it), the program crashes:

CGameRules *pGameRules = new CGameRules;
pGameRules->SendTextMessage(eTextMessageConsole, "$4test", eRMI_ToClientChannel, channelId);
delete(pGameRules);

This was experimenting whether something in the Aurora64 class file was causing the crash (it wasn't).

However when placed inside the same class, the program works perfectly with no crashes:

SendTextMessage(eTextMessageConsole, "$4test", eRMI_ToClientChannel, channelId);

Other than the pointer, the code is functionally identical (using the same input values).


The call stack is:

Aurora64.dll!IGameObject::GetEntityId() Line 301    C+Aurora64.dll!IGameObject::InvokeRMI_Primitive<CGameRules::MethodInfo_ClTextMessage,
          CGameRules::TextMessageParams>(const CGameRules::MethodInfo_ClTextMessage method, 
          const CGameRules::TextMessageParams
            & params, unsigned int where,
          IRMIListener * pListener, int userId, int channel, unsigned int dependentId)
          Line 281  C++
Aurora64.dll!IGameObject::InvokeRMI<CGameRules::MethodInfo_ClTextMessage,
          CGameRules::TextMessageParams>(const
          CGameRules::MethodInfo_ClTextMessage method, const CGameRules::TextMessageParams 
          & params, unsigned int where, int channel) 
          Line 275  C++
Aurora64.dll!CGameRules::SendTextMessage(ETextMessageType type, const char * msg, unsigned int
          to, int channelId, const char * p0, const char * p1, const char * p2, 
          const char * p3)
          Line 3075 C++
Aurora64.dll!CGameRules::OnClientConnect(int channelId, bool isReset) Line 596  C++


I don't understand why it's crashing... the code should technically work since the exact same function is being called, with the exact same input.

I have the source-code on GitHub should it be required (it does not have the Aurora64 class as it's another project based on the one from GitHub, but the source hasn't been changed). It's also likely that to debug it the Crysis Wars game and dedicated server package would be required, making it harder for anyone here to debug.

The problem with this might be something really obvious that I'm missing.

What am I doing wrong?


The SendTextMessage method:

int CScriptBind_GameRules::SendTextMessage(IFunctionHandler *pH, int type, const char *msg)
{
    CGameRules *pGameRules=GetGameRules(pH);

    if (!pGameRules)
        return pH->EndFunction();

    int to=eRMI_ToAllClients;
    int channelId=-1;

    if (pH->GetParamCount()>2)
        pH->GetParam(3, to);

    if (pH->GetParamCount()>3)
    {
        if (pH->GetParamType(4)==svtPointer)
        {
            ScriptHandle playerId;
            pH->GetParam(4, playerId);

            channelId=pGameRules->GetChannelId((EntityId)playerId.n);
        }
        else if (pH->GetParamType(4)==svtNumber)
            pH->GetParam(4, channelId);
    }

    if (pH->GetParamCount()>4)
    {
        string p[4];
        for (int i=0;i<pH->GetParamCount()-4;i++)
        {
            switch(pH->GetParamType(5+i))
            {
            case svtPointer:
                {
                    ScriptHandle sh;
                    pH->GetParam(5+i, sh);

                    if (IEntity *pEntity=gEnv->pEntitySystem->GetEntity((EntityId)sh.n))
                        p[i]=pEntity->GetName();
                }
                break;
            default:
                {
                    ScriptAnyValue value;
                    pH->GetParamAny(5+i, value);
                    switch(value.GetVarType())
                    {
                    case svtNumber:
                        p[i].Format("%g", value.number);
                        break;
                    case svtString:
                        p[i]=value.str;
                        break;
                    case svtBool:
                        p[i]=value.b?"true":"false";
                        break;
                    default:
                        break;
                    }           
                }
                break;
            }
        }
        pGameRules->SendTextMessage((ETextMessageType)type, msg, to, channelId, 
            p[0].empty()?0:p[0].c_str(),
            p[1].empty()?0:p[1].c_str(),
            p[2].empty()?0:p[2].c_str(),
            p[3].empty()?0:p[3].c_str()
            );
    }
    else
        pGameRules->SendTextMessage((ETextMessageType)type, msg, to, channelId);

    return pH->EndFunction();
}

error when runing .cpp file in terminal using g++

I trying RabbitMQ + C++. Working on linux ubuntu 16.04. Have working code and when I compile using CLion all works fine. I have peace of code what I need to run with root, so I need to run it using g++.

ERROR FROM TERMINAL

In function `main':
receiveUNPW.cpp:(.text+0x8e8): undefined reference to `SimplePocoHandler::SimplePocoHandler(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned short)'
receiveUNPW.cpp:(.text+0xc9c): undefined reference to `SimplePocoHandler::loop()'
receiveUNPW.cpp:(.text+0xcce): undefined reference to `SimplePocoHandler::~SimplePocoHandler()'
receiveUNPW.cpp:(.text+0xea7): undefined reference to `SimplePocoHandler::~SimplePocoHandler()'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libamqpcpp.so: undefined reference to `pthread_create'

I write :

g++ -std=c++11 receiveUNPW.cpp -o receiveUNPW -lcrypt -lPocoNet -lPocoFoundation -lamqpcpp 

CMakeList.txt

cmake_minimum_required(VERSION 3.5)
project(test)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

add_library(poco_simple_handler SimplePocoHandler.cpp SimplePocoHandler.h)
target_link_libraries(poco_simple_handler PocoNet PocoFoundation crypt )

set(PROGS
        sendUNPW
        receiveUNPW
        )

foreach(item ${PROGS})
    add_executable(${item} "${item}.cpp")
    target_link_libraries(${item} amqpcpp poco_simple_handler PocoNet PocoFoundation crypt)
endforeach(item)

MY IDEA

As can see when I use g++ it can't find reference to SimplePocoHandler. In CmakeList.txt i have

add_library(poco_simple_handler SimplePocoHandler.cpp SimplePocoHandler.h)
target_link_libraries(poco_simple_handler PocoNet PocoFoundation crypt )

so when I compile in CLion all works fine. So seems I need to do the same when I using g++. But I don't know how to do it, any suggestions or explanations would be great.

I don't share my receiveUNPW.cpp code, but it's almost similar to that receiver.cpp what you can see there and also I don't have any error there, in CLion all works fine, I just need to run my program using terminal with root permissions.

Can I use the iterator Libraries' Access Functions on Nonstandard Containers?

The iterator library has been introducing a lot of access functions over the course of C++11, C++14, and C++17:

  • begin/end
  • cbegin/cend
  • crbegin/crend
  • data
  • empty
  • rbegin/rend
  • size

Can I use these on any container, even nonstandard containers (provided they supply an accessible corresponding method?) For example given a QVector foo can I do this:

const auto bar = begin(foo);

comparison of two auto variables

#include <iostream>

using namespace std;

int main()
{
    auto a{1};
    auto b{1};
    if (a==b)
    {
        cout << "equal";
    }
    return 0;
}

Why does the above C++ code return an error in g++ compiler with c++11 standard, instead of printing "equal" as output?

test.cpp:9:14: error: no match for ‘operator==’ (operand types are ‘std::initializer_list’ and ‘std::initializer_list’) if (a==b) ^

What are the rules of field-by-field constructor generation?

I have found that the possibility of usage of initializer list syntax for a class depends on whether or not the class fields have default value. Why?

To be precise, consider the following code:

class S
{
public:
  int a;
};
...
int a;
S s{ a };

It compiles with no problems. But if I add default value to the class field, it stops building:

class S
{
public:
  int a = 0;
};
...
int a;
S s{ a };

Error   1   error C2440: 'initializing' : cannot convert from 'initializer-list' to 'S'

So, the questions are: why? what else influences such constructor generation?

Template partial specialization for multiple types overriding member function

I have class member functions defined as follows, providing a specification for one of them and letting the user provide their own specification for others:

template <typename T>
class Foo {
    // specialization provided for integral types
    template <typename Enable = T>
    typename std::enable_if<std::is_integral<Enable>::value, size_t>::type
        bar(const T& value);

    // provide your own specialization for other types
    template <typename Enable = T>
    typename std::enable_if<!std::is_integral<Enable>::value, size_t>::type
        bar(const T& value);
};

template <typename T>
template <typename Enable>
typename std::enable_if<std::is_integral<Enable>::value, size_t>::type
    Foo<T>::bar(const T& value) {
    ...
}

Now, I'd like to provide a specialization for the function that will work for integral pair types. I have a template metafunction checking for integral pairs defined as follows:

template <typename T>
struct is_integral_pair : std::false_type {}; 

template <typename T1, typename T2> 
struct is_integral_pair<std::pair<T1, T2>> {
    static const bool value =
        std::is_integral<T1>::value && std::is_integral<T2>::value;
};

Is it possible for me to provide my own specialization such that it works for all integer pairs, perhaps using the template metafunction I defined above?

Can not use C++11 in Qt

Since Qt 5.7, C++11 support is mandatory. For some reason one large old project does not accept the C++11 arguments. It doesn't matter if I use "CONFIG += c++11" or any other; C++11 only features do not work and therefor I can not compile the project.

The compiler arguments do contain "-std=c++11 -std=c++0x" if I use "CONFIG += c++11" in the .pro file. The target platform is Android ArmV7.

Any idea is welcome :)

how to execute a classes object's method simultaneously?

i'm new to multi threading, while i try to develop an application which processes a file i'm stuck at a point. below is the detailed description. please help.

my application reads a directory and loads all the files into class objects. the File class contains the data of the file along with few operational methods. after loading all[limited by constant] the files into memory i want to execute a method void processFile() for each object. i'm thinking to go to multi threading to improve performance so please tell me a way to achieve this.

my class interface:

class D3v_File{
private:
       string* lines;
       string fname;
       int    fileState;
       int    T_lineCnt;
       int    C_lineCnt;
       static int fileCnt;

public:
      D3v_File(const string& f_name);
      string next_line();
      void load_now();
      void process_file();
      ~D3_File();
};

so in my code some where i have a container

vector < D3v_File > File_Obs;

i want to execute the process_file function of objects in the container File_obs parallel.

suggest me the best approach.

Why are there so many ways to initialize variables in C++?

int a=3;
int b(3);
int c{3}; 

Why are there so many ways to initialize variables in C++, is there any difference in these methods?

mardi 28 juin 2016

How to create alias to template method

From this link (1056. Template aliases, member definitions, and the current instantiation) I realised that, We can create alias in templates, for example we could do as below

template<typename T>
using Vec = std::vector<int>

How can I create alias for a template method, I tried below but it throws compilation error error: missing template arguments before '.' token

#include <iostream>
using namespace std;

template <class T> struct A 
{
    float g(T x){return(x*0.01);}
};

template <class T> using B = A<T>;

int main() 
{
    B.g<int>(10);
    // your code goes here
    return 0;
}

I'm not sure how to create alias for template method, Please someone shed light on this.

Compile error when using a member of a user-defined literal

When compiling this code (without any header)

template <typename T>
struct Temperature {
    T temp;

    explicit Temperature(T t)
        : temp(t)
    {}
};

Temperature<long double> operator "" _f (long double t)
{
    return Temperature<long double>((t - 32) / 1.8);
}

int main()
{
    auto t = 100.0_f;
    t.temp;

    100.0_f.temp; // ERROR AT THIS LINE
    return 0;
}

The compilers (both g++ 4.8 and clang++ 3.4 on Ubuntu 14.04) will complain that

error: unable to find numeric literal operator ‘operator"" _f.temp’
     100.0_f.temp;
     ^

It seems that the _f.temp is considered as a suffix there. Why do the compilers parse it like that, instead of stopping at the dot?

How to check libmongoc (mongodb c driver) version?

I'm building mongodb cxx driver (c++11) in CentOS 6.5. Following this page, I have to install libmongoc first. But after I built and make installed the newest libmongoc(version:1.3.5), I still receive fews error while installing mongodb cxx driver such as "Checking for module 'libmongoc-1.0>=1.3.4' ".

So I'm afraid I've not installed libmongoc correctly, and I wanna know how to get the libmongoc version, Thanks.

How to get the number of digit in double value in c++?

I have tried to get the number of digit from double value but it is not working properly. Can you please help me to get the exact number of digit in double.

I have tried as :

int main()
{
    double value = 123456.05;
    std::cout<<"number of digit::"<<((int)std::log10(value ) + 1);
}

output::

number of digit::6

But the number of digit is 9. How to get exact number of digit. In my case 9.

If I use CreateEx( ... ) after the main window was created I cannot FindWindow( ... )

I have the following code to create a 'message only' window, the window is always created fine, the problem happens when it is created.

Process A

...
auto hInstance = ::GetModuleHandle( nullptr );
WNDCLASSEX wcx;
wcx.cbSize = sizeof(wcx);
wcx.style = 0;
wcx.lpfnWndProc = MyWinProc;
wcx.cbClsExtra = 0;
wcx.cbWndExtra = 0;
wcx.hInstance = hInstance;
wcx.hIcon = LoadIcon(NULL, IDI_APPLICATION); 
wcx.hCursor = LoadCursor(NULL, IDC_ARROW);
wcx.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH);
wcx.lpszMenuName = L"MainMenu";
wcx.lpszClassName = L"MyDummyClass";
wcx.hIconSm = (HICON)LoadImage(hInstance,
              MAKEINTRESOURCE(5),
              IMAGE_ICON,
              GetSystemMetrics(SM_CXSMICON),
              GetSystemMetrics(SM_CYSMICON),
              LR_DEFAULTCOLOR);

if (!RegisterClassEx(&wcx))
{
  throw "Bad 1.";
}

if (!this->CWnd::CreateEx(0, L"MyDummyClass", L"MyDummyWindow", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr))
{
  throw "Bad 2.";
}

Process B

 auto myWnd = FindWindow( L"MyDummyClass");

Now the problem I have is if process A create the window before OnInitDialog is called then process B can find the window.

But if process A creates the window at any other time after the main window was created then process B cannot find the window any longer.

In both cases the message pump is called fine, the window is created as expected, I just cannot FindWindow when I create it after the main application is started.

Why would that be, and how can I work around that?

std::basic_ostream is inaccessible in C++

I get the following error and I'm not sure what the issue is

1 IntelliSense: "std::basic_ostream<_Elem, _Traits>::basic_ostream(const std::basic_ostream<_Elem, _Traits>::_Myt &_Right) [with _Elem=char, _Traits=std::char_traits]" (declared at line 82 of "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\ostream") is inaccessible

Book.cpp

ostream operator<< (ostream& out, const Book & b){
    out << "Title: " << b.my_Title << endl;
    out << "Author: " << b.my_Author << endl;
    out << "Number of time checkout out: " << b.my_NumberOfTimesCheckedOut;
    return(out);
}

I get the issue with the return(out);

Book.h

#ifndef BOOK_H
#define BOOK_H
#include <string>
using namespace std;
namespace CS20A
{
    class Book {
    public:
        Book();
        Book( string author, string title );
        string getTitle() const;
        string getAuthor() const;
        int getNumberOfTimesCheckedOut() const;
        void increaseNumberOfTimesCheckedOut( int amount=1 );
        friend ostream operator<< ( ostream& out, const Book & b );
    private:
        string my_Author;
        string my_Title;
        int my_NumberOfTimesCheckedOut;
    };
};
#endif

I don't even understand what the error is telling me

C++11 result_of deducing my function type failed

I was trying a program below:

#include<type_traits>
using namespace std;
template <class F, class R = typename result_of<F()>::type>
R call(F& f) { return f(); }
int answer() { return 42; }

int main()
{
    call(answer); 
    return 0;
}

"call(answer)" fails to compile

VC says 'R call(F&)' could not deduce template argument for 'R'

GCC says |note: template argument deduction/substitution failed:|error: function returning a function

I'm not sure if a "function name" could be used for templates. Where did I get wrong, how to make my call(answer) work?