vendredi 31 juillet 2015

where does the pointer created by new get deleted in this code?

I am reading the IB api C++ code, and have found the following class structure

class EWrapper;

class EClientSocketBase{
 public:
 EClientSocketBase( EWrapper *ptr): m_pEWrapper(ptr){}
 ~EClientSocketBase(){ }
 // some methods
 private:
 EWrapper *m_pEWrapper;
 // some other data members
};

class EPosixClientSocket : public EClientSocketBase{
// some methods and data members
EPosixClientSocket( EWrapper *ptr) : EClientSocketBase( ptr){}
~EPosixClientSocket(){}
};

class PosixTestClient : public EWrapper{
public:
PosixTestClient(): m_pClient(new EPosixClientSocket(this)){}
~PosixTestClient(){}
// some other methods 
private:
std::auto_ptr<EPosixClientSocket> m_pClient;
// some other methods and data members
};

I feel very uncomfortable about initializing EPosixClientSocket with this, but somehow I can not articulate what exactly the mistake is.

  1. An question to ask is that where the pointer m_pClient, and pointer m_pEWrapper get deleted respectively?
  2. Is there something wrong in this code? If yes, what is it? If not, is it a good practice to write code like this?

Inline assembly inside C++ for data conversion

I am trying to write a C++ code for conversion of assembly dq 3FA999999999999Ah into C++ double. What to type inside asm block? I dont know how to take out the value.

int main()
{
    double x;

    asm
    {
        dq  3FA999999999999Ah
        mov x,?????
    }

    std::cout<<x<<std::endl;

    return 0;
}

Do derived classes need to implement move semantics when a base provides it?

I finished reading Thomas Becker's "C++ Rvalue References". I have a couple questions on Rvalues and Rvalue references.

Suppose I have a simple array class:

template <class T>
MyArray
{
    ...
    T* m_ptr;
};

Further suppose it provides:

#if(__cplusplus >= 201103L)
MyArray(MyArray&& t)
{
    std::swap(*this, t);
}
MyArray operator=(MyArray&& t)
{
    std::swap(*this, t);
    return *this;
}
#endif

Now, suppose I have a derived class that does not add new data members:

MyImprovedArray : public MyArray
{
    ...
};

What is required of MyImprovedArray?

Does it need a MyImprovedArray(MyImprovedArray&&) and MyImprovedArray& operator=(MyImprovedArray&&) also? If so, does it only need to perform the base class std::move? Or does it need to perform the std::swap too?

MyImprovedArray(MyImprovedArray&& t)
    : MyArray(std::move(t))
{
}

Is partial specialization in a cpp file not "well-formed"

This a follow-up to [question]: No generated code for explicitly specialized template even with explicit instantiation.

I am using partial specializations in a .cpp file to handle special cases while not forcing all the code into a header file. A simplified example of what I'm doing is given below. This works with both gcc and clang, but given the answer to the question above, I'm wondering if I'm just getting lucky that the linker is finding compatible symbols.

I'm starting with a class template defined in foo.hpp:

#pragma once

template <typename T1, typename T2>
class foo
{
public:
  foo (T1 t1, T2 t2) : d_t1(t1), d_t2(t2) {}
  ~foo () = default;

  void print ();
private:
  T1 d_t1;
  T2 d_t2;
};

Note that the print() method is declared, but not defined.

Now in the foo.cpp, I define the print() method.

#include <iostream>

template <typename T1, typename T2>
void
foo<T1,T2>::print()
{
    std::cout << "T1 is: ";
    d_t1.print();
    std::cout << std::endl;
    std::cout << "T2 is: ";
    d_t2.print();
    std::cout << std::endl << std::endl;
}

Note that this implementation assumes that both T1 and T2 will have a method called print(). In my real world code, the types which are used as arguments to this template usually conform to this interface, but sometimes they don't and I deal with that through partial specialization in the .cpp file. This template is not meant for really generic usage, it only needs to work with a small number of types which I know up-front.

So for instance, I might have 3 types such as

class HasPrint
{
public:
  HasPrint () = default;
  ~HasPrint () = default;

  void print ();

};

class AlsoHasPrint
{
public:
  AlsoHasPrint () = default;
  ~AlsoHasPrint () = default;

  void print ();

};

class NoPrint
{
public:
  NoPrint () = default;
  ~NoPrint () = default;

  void noPrint ();

};

Note that 'HasPrint' and 'AlsoHasPrint' classes have a print() method, while the 'NoPrint' class has a noPrint() method. In the bodies of these classes the print/noPrint methods simply print the name of the class.

To handle the case of someone using NoPrint as one of the template arguments, I define a partial specialization in the foo.cpp file:

template <typename T2>
class foo <NoPrint, T2>
{
public:
  foo (NoPrint n1, T2 t2) : d_n1(n1), d_t2(t2) {}
  ~foo () = default;

  void print ()
  {
    std::cout << "NoPrint is: ";
    d_n1.noPrint();
    std::cout << std::endl;
    std::cout << "T2 is: ";
    d_t2.print();
    std::cout << std::endl;
  }
private:
  NoPrint d_n1;
  T2 d_t2;
};

Then to get all the code I need generated for all the permutations that I use, I include (in the foo.cpp file) the following explicit instantiations of foo.

template class foo<HasPrint, HasPrint>;
template class foo<HasPrint, AlsoHasPrint>;
template class foo<AlsoHasPrint, AlsoHasPrint>;
template class foo<NoPrint, HasPrint>;

The result of the last explicit instantiation is that code is generated for an expansion of the template using the NoPrint object and calling the method noPrint().

In a separate test.cpp file, I have the driver for my test program.

#include "foo.hpp"
#include "hasprint.hpp"
#include "alsohasprint.hpp"
#include "noprint.hpp"

int
main (int argc, char** argv)
{
  HasPrint h1;
  HasPrint h2;
  AlsoHasPrint a1;
  NoPrint n1;
  foo<HasPrint, HasPrint> f1 (h1, h2);
  foo<HasPrint, AlsoHasPrint> f2 (h1, a1);
  foo<AlsoHasPrint, AlsoHasPrint> f3 (a1, a1);
  foo<NoPrint, HasPrint> f4 (n1, h1);


  f1.print();
  f2.print();
  f3.print();
  f4.print();
}

This works as expected on both gcc 4.8.3 and clang 3.2. The result is:

T1 is: HasPrint
T2 is: HasPrint

T1 is: HasPrint
T2 is: AlsoHasPrint

T1 is: AlsoHasPrint
T2 is: AlsoHasPrint

NoPrint is: NoPrint
T2 is: HasPrint

This keeps the header for foo.hpp nice and clean at the expense of needing to use explicit instantiation for each set of types for which I use the template, and a partial specialization if one of the argument types does not conform to the interface.

Given that I'm using the type Foo< NoPrint, HasPrint > in the test driver, without informing the compiler that a specialization exists, is this "well-formed" or am I just getting lucky?

Thanks

How to initialize class member std::function?

I am trying to create a class with an std::function member:

class Widget {
public:
  std::function<int(double)> call_foo;

  Widget(std::function<int(double)> call_func)
    : call_foo(call_func)
  {};

};

However, when I try to initialize the class my code fails because 'function' in namespace 'std' does not name a template type

const int f(double x){
  if(x > 5.0){
    return 22;
  }
  return 17;
}

int main()
{
  std::function<int(double)> f1 = f;
  Widget p(f1);

}

The full set of errors is below:

widget.cpp:5:8: error: ‘function’ in namespace ‘std’ does not name a template type
   std::function<int(double)> call_foo;
        ^
widget.cpp:8:23: error: expected ‘)’ before ‘<’ token
   Widget(std::function<int(double)> call_func)
                       ^
widget.cpp: In function ‘int main()’:
widget.cpp:23:3: error: ‘function’ is not a member of ‘std’
   std::function<int(double)> f1 = f;
   ^
widget.cpp:23:17: error: expected primary-expression before ‘int’
   std::function<int(double)> f1 = f;
                 ^
widget.cpp:24:12: error: ‘f1’ was not declared in this scope
   Widget p(f1);

I also tried initializing with f directly, but this produces an error as well. What's wrong with my syntax?

Math.h macro collisions

Macro DOMAIN in math.h collides with enums and possibly other types. I don't know what to make of it.

#include <algorithm>

enum Type { DOMAIN };


int main(){
    Type t = Type::DOMAIN;
    return 0;

}

Compile with flag -std=c++11. The C99 version of this code compiles perfectly fine though:

#include <algorithm>

enum Type { DOMAIN };


int main(){
    Type t = DOMAIN;
    return 0;

}

gcc/clang not generating code for fully specialized template even with explicit instantiation

I'm getting consistent behavior from both gcc 4.8.3 and clang 3.2, but do not understand why it is happening. Despite the fact that I have an explicit instantiation for a templatized class, the code is not being generated and I get an undefined symbol when I am using a fully specialized instance of the template.

I have a simple class template definition in a file 'temp.hpp'

#pragma once

template <typename T1>
class C 
{
public:
  C (T1 c) : d_c(c) {};
  ~C () = default;

  void print ();
private:
  T1 d_c;
};

Note that the method 'print()' is declared, but not defined here. I want the definition in the .cpp file and it will be specialized for different types.

So in the temp.cpp file I have the default definition of the print() method

#include "temp.hpp"
#include <iostream>

template<typename T1>
void
C<T1>::print ()
{
  std::cout << "Printing: " << d_c << std::endl;
}

followed by a specialization of the class for the type 'float':

template <>
class C <float>
{
public:
  C (float f) : d_f(f) {};
  ~C () = default;

  void print ()
  {
    std::cout << "float: " << d_f << std::endl;
  }

private:
  float d_f;
};

and since the definitions are in the .cpp file I must explicitly instantiate all the specializations that I will be using. So I have:

template class C<int>;
template class C<float>;

The driver for my test looks like this in test.cpp:

#include "temp.hpp"

int
main (int argc, char** argv)
{
  int i = 1;
  C<int> c_int(i);

  float f = 1.2;
  C<float> c_float(f);

  c_int.print();
  c_float.print();
}

Upon compiling and linking this I get error:

test.cpp: undefined reference to `C<float>::print()'

The object code for the C< int > is properly generated. I can see it using nm:

nm -C temp.o
...
0000000000000000 W C<int>::print()
0000000000000000 W C<int>::C(int)
0000000000000000 W C<int>::C(int)
...

As I mentioned earlier, this is consistent with gcc and clang so I'm assuming there is some lanuguage rule I don't understand here.

Note that if I add a usage of the print () method in file temp.cpp, then the code is generated, but that is silly and in my real code would be impossible. For this simple testcase it would look like:

void foo () 
{
  C<float> s(1.3);
  s.print();
}

In the real code which motivated this little test my template has 3 template arguments which combine to expand into about 30 permutations of the code. There are one or two of those for which I need a specialization which does something different, but the other 28 I can leave alone.

Any pointers on where I've gone wrong or a language reference for why the explicit instantiation of should not generate code are greatly appreciated. I've spent 1/2 a day reading all the other stackoverflow posts on explicit instantiation and believe I am using it correctly.

Thanks

Smart pointer to ofstream or cout

I'm making a simple logging class with a pointer to either a std::ofstream or std::cerr. Is there any simple way to use a smart pointer for auto clean-up regardless of which stream is used? The code must compile on clang++, g++, and VS2013.

Code

#include <iostream>
#include <fstream>
#include <string>

class Logger {
private:
    std::ostream * output_stream{ nullptr };
    bool using_file{ false };
public:
    Logger()
    {
        output_stream = &std::cerr;
        using_file = false;
    }
    Logger(std::string file)
    {
        output_stream = new std::ofstream(file);
        using_file = true;
    }
    ~Logger()
    {
        if (using_file)
        {
            delete output_stream;
        }
    }
    template<typename T>
    void log(T info)
    {
        *output_stream << info << std::endl;
    }
};

class tmp {
    int i{ 4 };
    friend std::ostream & operator<<(std::ostream &os, const tmp& p);
};

std::ostream &operator<<(std::ostream &os, const tmp& p)
{
    return os << p.i;
}

int main()
{
    tmp t;
    Logger logger;
    logger.log(t);
    system("pause");
    return 0;
}

Attempts

std::unique_ptr

I can use std::unique_ptr for the file like so:

std::unique_ptr<std::ostream> p;
p = std::make_unique<std::ofstream>("file.txt");
*p << "hi there" << std::endl;

Trying this with std::cout warns me about a deleted function (assuming that's the constructor.

std::unique_ptr<std::ostream> p2;
p2 = std::make_unique<std::ostream>(std::cout);
*p2 << "hey" << std::endl;

std::shared_ptr

Because std::unique_ptr is only for owning things, and std::cout shouldn't be owned, I thought I'd try std::shared_ptr

std::shared_ptr<std::ostream> p;
p = std::make_shared<std::ostream>(std::cout);
*p << "hola" << std::endl;

It gives me the same deleted constructor error. p = &std::cout complains about a type mismatch, so it's also not working.

Semantic errors with overload resolution for init-list-as-function-argument and templates

I've configured Eclipse CDT for C++11 use in its continual build process, but certain expressions are still causing semantic errors even though they compile properly using g++ 4.9.2 and clang++ 3.8.0. Namely, braced init lists supplied as function arguments are not matched to the arguments' corresponding std::initializer_list constructors and the right version of LLVM's cast function is not matched to its supplied arguments either. Is Eclipse CDT using an older, internal parser that doesn't support such C++11 functionality rather than delegating to the more modern external GCC toolchain, which it does detect?

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"

using namespace llvm;

// i32 @myFunc1(i32, i32), i32 @myFunc2(i32, i32)
SmallVector<Function*, 2> getMyFuncs(Module& M) {
  Type* i32 = Type::getInt32Ty(M.getContext());

  // error #1 reported
  FunctionType* FT = FunctionType::get(i32, {i32, i32}, false); 

 // error #2 reported
  Function* F1 = cast<Function>(M.getOrInsertFunction("myFunc1", FT));

  // no error with implicit matching of ArrayRef(const std::initializer_list<T>&) here
  ArrayRef<Type*> ArgTypes = {i32, i32};
  FT = FunctionType::get(i32, ArgTypes, false);

  // error #2 reported
  Function* F2 = cast<Function>(M.getOrInsertFunction("myFunc2", FT));

   // no error with implicit matching of SmallVector(std::initializer_list<T>) here
  return {F1, F2};
}

Error #1

Invalid arguments '
Candidates are:
llvm::FunctionType * get(llvm::Type *, llvm::ArrayRef, bool)
llvm::FunctionType * get(llvm::Type *, bool)

Error #2

Invalid arguments '
Candidates are:
llvm::cast_retty<#0,#1 *>::ret_type cast(#1 *) std::enable_if::ret_type>::type cast(const #1 &)
llvm::cast_retty<#0,#1>::ret_type cast(#1 &)
'

Implementing a custom comparator with a functor template

I want to write custom comparators for functions like lower_bound, find, etc. Below is an example of a custom comparator implemented with a functor that takes another function object (std::less, std::greater, etc) and use it to compare the first element of a pair with the second argument of the function.

template <template <typename> class P = std::less>
struct custom_comp {
    template <class T1, class T2>
    bool operator()(const std::pair<T1, T2>& pair, const T1& val)
    {
            return P<T1>()(pair.first, val);
    }
}

Usage example:

vector<pair<int,int>> vec = {{1, 4}, {3, 3}, {5, 6}, {8, 8}};
auto first = lower_bound(begin(vec), end(vec), 5, custom_comp<>());

However the <>() bothers me, I feel it takes away readability. Is there a way to get rid of it? (perhaps changing the functor for another kind of structure).

btw: I don't want to use lambdas because I want to reuse these custom comparators and even extend them to take more template arguments (like custom filters, e.g a functor that takes a pair and returns pair.first, or a functor that takes the mean of a vector, etc).

does std::unique_lock::try_lock_until busy wait?

I'm thinking of using

auto now = std::chrono::high_resolution_clock::now();

std::unique_lock<std::mutex> lock(mutex, std::defer_lock);
if(lock.try_lock_until(now + std::chrono::milliseconds(15))
{
    // swap some buffer pointers...
    lock.unlock();
}

However, it's not clear to me from the documentation if try_lock_until is implemented as a busy wait or if the thread will yield /sleep in between tries (my desired behavior). Is this the best way to query a lock while minimizing thread resource usage?

Using existing std::thread(s) for doing work

I have an algorithm that takes a long time to run (hours to days) with many iterations of the same loop.

I want to use the std::thread library as part of C++ 11 as much as possible.

I would like to start up nTread worker threads and then have them sit idle until instructed to do operation "taskNumber".

Can I do this with future and promises?

Is there a better way to do this?

In the below code what I am trying to do is:

  1. Start up 6 worker threads. They start off waiting to do any work.
  2. Tell the 6 worker threads to do task 0. The main thread waits for them all to completed.
  3. Tell the 6 worker threads to do task 1. The main thread waits for them all to completed.
  4. Tell the 6 worker threads to do task 2. The main thread waits for them all to completed.
  5. Tell the 6 worker threads to do task 3. The main thread waits for them all to completed.
  6. repeat steps 1) - 1) 100 times.

What I am trying is as follows:

#include <iostream>
#include <thread>
#include <future>
#include <vector>

std::vector<std::promise<int>> readyPromise;
std::vector<std::promise<bool>> donePromise;

void initiazer(int threadNumber)
{
    while (true) {
        // Wait to see if it is ready to run
        std::future<int> readyFuture = readyPromise[threadNumber].get_future();
        int taskNumber = readyFuture.get();

        std::cout<<"Inside Thread: " << threadNumber << " doing task: " << taskNumber << std::endl;

        // tell it that this is done
        donePromise[threadNumber].set_value(true);

        if (taskNumber == 9)
            exit(0);
    }
}

int main()
{
    int nThread = 6;

    // Create the promises and future
    std::vector<std::future<bool>> doneFuture;
    for (int i=0; i<=nThread; ++i) {
        readyPromise.push_back(std::promise<int>());
        donePromise.push_back(std::promise<bool>());
        doneFuture.push_back(std::future<bool>());
    }

    // Create the threads
    std::vector<std::thread> threads;
    std::cout << "Create nThread threads" << std::endl;
    for (int i=0; i<=nThread; ++i)
        threads.push_back(std::thread(initiazer, i));

    // Loop 100 times
    for (int j=0; j<100; j++) {
        for (int task=0; task<4; j++) {
            // tell the threads to go
            for (int i=0; i<nThread; i++) {
                doneFuture[i] = donePromise[nThread].get_future();
                readyPromise[i].set_value(task);
            }

            // Nothing happening here.

            // Wait for the threads to finish
            for (int i=0; i<nThread; i++) {
                doneFuture[i].get();
            }
            // Do some work on the main thread.
        }
    }

    int task = 9; // Tell threads to exit
    for (int i=0; i<nThread; i++) {
        doneFuture[i] = donePromise[nThread].get_future();
        readyPromise[i].set_value(task);
    }

    // Wait for all the threads to exit.
    for (int i=0; i<nThread; i++) {
        threads[i].join();
    }

    return 0;
}

unique_ptr and default constructible pointer

Recently I tried to reinvent scope guard via std::unique_ptr:

#include <type_traits>
#include <utility>
#include <memory>
#include <iostream>

#include <cstdlib>
#include <cassert>

namespace
{

template< typename lambda >
auto
make_scope_guard(lambda && _lambda)
{
    struct lambda_caller
    {

        using pointer = std::decay_t< lambda >;

        void
        operator () (pointer l) const noexcept
        {
            std::forward< lambda >(l)();
        }

    };
    return std::unique_ptr< std::decay_t< lambda >, lambda_caller >(std::forward< lambda >(_lambda));
}

}

int
main()
{
    std::cout << 1 << std::endl;
    {
        std::cout << 2 << std::endl;
        [[gnu::unused]] auto && guard_ = make_scope_guard([&] { std::cout << __PRETTY_FUNCTION__ << std::endl; });
        std::cout << 3 << std::endl;
    }
    std::cout << 5 << std::endl;
    return EXIT_SUCCESS;
}

Such an approach works fine for simple pointer to free function void f() { std::cout << 4 << std::endl; } passed to make_scope_guard, but not for any lambda passed to make_scope_guard.

This is due to an abundance of ... = pointer() into the std::unique_ptr definition (function default parameter, defaulting data memebers etc), but I can't find the DefaultConstructible requirement for pointer into this article.

Is it mandatory, that the pointer should match the std::is_default_constructible requirement?

It tested against libc++ and against libstdc++ using not too old clang++ -std=gnu++1z.

Seems, there should be language extension for lambdas: if auto l = [] {}; then using L = decltype(l) is equivalent to struct L { constexpr void operator () () const noexcept { ; } }, isn't it?

invalid conversion from const char* to int

I have four files in c++

BankAccount.h
BankDatabase.h
Main.cpp 

BankAccount.h

#include <string>
class BankAccount
{
    public:
        BankAccount(int accNumber,const std::string& accName);
        void setAccNumber(const int accNumber);
        int getAccNumber() const;
        void setAccName(const std::string& clientName);
        std::string getAccName() const ;
    protected:
        int mAccNumber;
        std::string mAccName;
};
BankAccount::BankAccount(const int accNumber,
        const std::string& accName):mAccNumber(accNumber),mAccName(accName){}
void BankAccount::setAccNumber(const int accNumber)
{
   mAccNumber = accNumber;     
}
void BankAccount::setAccName(const std::string& accName)
{
    mAccName = accName;
}
int BankAccount::getAccNumber() const 
{
    return mAccNumber;
}
std::string BankAccount::getAccName() const {
    return mAccName;
}

BankDatabase.h

#include <map>
#include <iostream>
#include <stdexcept>
#include "BankAccount.h"
class BankDatabase
{
    public:
        BankDatabase();
        void addAccount(const BankAccount& acc);
        void deleteAccount(int accNumber);
        BankAccount& findAccount(int accNumber) 
            throw (std::out_of_range);
        BankAccount& findAccount(std::string& accName) 
            throw (std::out_of_range);
        void mergeDatabase(BankDatabase& db);
    protected:
        std::map<int,BankAccount> mAccounts;
};
BankDatabase::BankDatabase(){}
void BankDatabase::addAccount(const BankAccount& acc)
{
    std::pair<std::map<int,BankAccount>::iterator,bool> res =  
        mAccounts.insert(std::make_pair(acc.getAccNumber(),acc));
    if(!res.second)
        std::cout << "Account cannot be  added ";
}
void  BankDatabase::deleteAccount(int accNumber) 
{
    if( mAccounts.count(accNumber))
        mAccounts.erase(accNumber);
}
BankAccount& BankDatabase::findAccount(int accNumber)
    throw(std::out_of_range)
{
    auto iter =  mAccounts.find(accNumber);
    if(iter != mAccounts.end())
        return iter->second;
    throw std::out_of_range("No account number with this name ");
}
BankAccount& BankDatabase::findAccount(std::string& accName) 
    throw(std::out_of_range)
{
    for(auto& p : mAccounts) {
        if ( p.second.getAccName() == accName )
            return p.second;
    }
    throw std::out_of_range(" No account with this name ");
}

Main.cpp

#include <iostream>
#include "BankDatabase.h"
int main()
{
    BankDatabase db;
    db.addAccount(BankAccount(1,"james"));
    db.addAccount(BankAccount(2,"johnson"));
    db.addAccount(BankAccount(3,"kamal"));
    db.addAccount(BankAccount(4,"appu"));
    // find account name based on account number
    std::cout << db.findAccount(1).getAccName();
    // find account number based on account name
    std::cout << db.findAccount("james");
    // delete an account
    db.deleteAccount(db.findAccount("james").getAccNumber());
    // find the account
    std::cout << db.findAccount("james");
    //Merge database
    db.mergeDatabase(db);
    return 0;
}

At the statement std::cout << db.findAccount("james"); I got an error:

error: invalid conversion from 'const char*' to 'int'

But I defined findAccount(int) and findAccount(string) in BankDatabase.h

Can someone help in this issue?

"Undefined reference to..." error without O1 optimization

I get error "undefined reference to..." while I'm trying to compile my project without O1 optimization. To simplify, assume that we have one class with constant and method:

Car.h

class Car {
 void getInfo();
 static constexpr const char * NAME = "sport car";
}

Car.cpp

void Car::getInfo() {
 //When I try to use constant NAME here, I get error "Undefined reference..."
}

I'm using C++11. Where can be the problem?

Why is following legal in C++?

Why is following code legal in C++?

bool a(false);

? I mean, the T a(VALUE) should call constructor right (let's suppose it's not parsed as function declaration)? But boolean is plain type, it doesn't have constructor. Or does it?

I'm using Visual Studio 2012 if it's relevant.

proper way of handling std::thread termination in child process after fork()

Frown as much as you want, I'm going to do it anyway :)

My question is: in the following code, what is the proper way to handle the termination of the std::thread in the subprocess generated by fork()? std::thread::detach() or std::thread::join()?

#include <thread>
#include <iostream>
#include <unistd.h>

struct A { 

   void Fork()
   {   
      std::thread t(&A::Parallel, this);
      pid_t pid = fork();
      if(pid) {
         //parent
         t.join();
      } else {
         //child
         t.join(); // OR t.detach()?
      }   
   }   

   void Parallel()
   {   
      std::cout << "asd" << std::endl;
   }   
};

int main() {
   A a;
   a.Fork();
   return 0;
}

I know that only the thread that calls fork() is duplicated, which means that the std::thread is actually doing nothing in the child process right? Hence my doubt.

Compile time encryption for strings using user-defined literals

I am aware that the new C++ standard allows for user-defined literals and that their generation can be done in compile time.

However, I am quite new to the whole template metaprogramming universe and I'm trying to get some examples going, but still without success, since it's the first time I have contact with this particular feature.

So let's say I have a string:

std::string tmp = "This is a test message";

And I would like to encrypt it at compile time using:

std::string tmp = "This is a test message"_encrypt;

Is it even possible what I'm trying to attempt?

I am currently using VS2015 so any help or feedback is appreciated.

why is void_t necessary to check for the existence of a member type?

When reading Barry's answer to Check if a given type has a inner template rebind, I thought:

Why do we need void_t at all?

Why does the following not work?

#include <iostream>

template <typename X, typename Y = X>
struct has_rebind : std::false_type {};

template <typename X>
struct has_rebind<X, typename X::template rebind<int>> : std::true_type {};

struct A { };
struct B { template <typename > struct rebind { }; };

int main() {
    std::cout << has_rebind<A>::value << std::endl;
    std::cout << has_rebind<B>::value << std::endl;
}

output

0
0

demo

Range based for loop with pointer to vector in C++11

Consider the following example:

vector<vector<char>*> *outer = new vector<vector<char>*>();
{
    vector<char> *inner = new vector<char>();

    inner->push_back(0);
    inner->push_back(1);
    inner->push_back(2);

    outer->push_back(inner);

    inner->push_back(3);
}

auto x = outer->at(0);

for (auto c : x) {
    cout << c << ",";
}

I would like to iterate through vector values of vector<char>* how can I accomplish that?

Thank you in advance!

cv-qualified struct's member is not similarly cv-qualified

According to this answer, the following code should be compiled without error:

#include <type_traits>

namespace
{

struct A { int i; };

volatile A a{};
static_assert(std::is_volatile< decltype(a) >{});
static_assert(std::is_volatile< decltype(a.i) >{});

}

but there is a hard error:

main.cpp:10:1: error: static_assert failed
static_assert(std::is_volatile< decltype(a.i) >{});
^             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.

Live example with clang 3.6.0.

Is it a clang bug or am I missing something substantial?

ADDITIONAL:

#include <type_traits>

namespace
{

struct A { int i; };

const A a{};
static_assert(std::is_const< decltype(a) >{});
static_assert(std::is_const< decltype(a.i) >{});

}

Exactly the same behaviour for the latter code snippet.

ADDITIONAL:

static_assert(std::is_volatile< std::remove_pointer_t< decltype(&a.i) > >{});

not cause an error.

Using a priority_queue of int with custom compare

I have numbers from 1 to n, and an array of priorities P of size n. I want to declare a priority queue using P as their priorities.

I don't want to define a new type of object that contains the number and its priority, I want to use a priority queue of int objects and pass a custom comparison object that depends on P to std::priority_queue. I tried the following but it doesn't work:

std::priority_queue<int, vector<int>, [P](int i, int j){ return P[i]<P[j]; }> PQ;

I also tried defining a class with a bool operator(int i, int j) {P[i] < P[j]} member and a constructor where I can pass P to it but that also didn't work.

How should I declare my priority queue?

Access Violation on Const Atomic Variable

When executing the following c++ code in Visual Studio 2012 it generates the following error: Access violation writing location 0xADDRESS. This "application" will compile and execute without issue if the variable "alwaysFalse" is non-const. What I don't understand is why when it's const it causes an access violation?

#include <atomic>
#include <iostream>

namespace
{

const std::atomic_bool alwaysFalse = ATOMIC_VAR_INIT(false);

}

int main(int argc, char* argv[])
{
    if (alwaysFalse)
        std::cout << "It's true" << std::endl;
    else
        std::cout << "It's false" << std::endl;
    return 0;
}

Passing each argument of a variadic function template into a function that returns void

Based on the recipe found here, I wrote the following:

void printInt(int a) {std::cout << a << std::endl;}

template <typename... Args>
void f(const Args &... args) {
    auto temp = {(printInt(args), void(), 0)...};
    auto a = temp; temp = a;
}

Two questions:

  1. What does this syntax mean: {(printInt(args), void(), 0)...}?

  2. I added the line auto a = temp; temp = a; in order to not get a warning about the unused variable temp. Is there a better way?

Are all template instantiations created at compile time?

After learning about variadic function templates that use recursion, I am wondering:

Are all template instantiations that can possibly be needed during the program's execution created at compile time? Is there such thing as instantiation on-the-fly?

Compile time Restricted Templates without use of boost

this is related to these two questions:

  1. standard c++11 way to remove all pointers of a type
  2. Compile Time Template restriction C++

the second one is mine

the issue is when i moved to TDM-GCC 64 the following code (previously working crashes) I made sure c++11 is enabled.

template<typename _Ty,
typename enable_if< is_base_of<OverVoid, remove_all_pointers<_Ty>::type>::value>::type>
class Move{
public:
    Move()
    {
        cout<<"### "<<remove_all_pointers<_Ty>::type::isOverVoid()<<endl;
    }
};


int main(){

    Move<Meta***> z;
    Move<Meta**> w;
    Move<Meta*> x;
    Move<Meta> y;

}

it displays the following error

Info: Internal Builder is used for build
g++ -std=c++0x -std=c++11 -std=gnu++11 -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\helllo_world.o" "..\\src\\helllo_world.cpp" 
In file included from ..\src\helllo_world.cpp:1:0:
..\src\Move.h:54:111: error: type/value mismatch at argument 2 in template parameter list for 'template<class, class> struct std::is_base_of'
 template<typename _Ty,class = typename std::enable_if<std::is_base_of<OverVoid, remove_all_pointers<_Ty>::type>::value>::type>
                                                                                                               ^
..\src\Move.h:54:111: note:   expected a type, got 'remove_all_pointers<T>::type'
..\src\Move.h:54:119: error: template argument 1 is invalid
 template<typename _Ty,class = typename std::enable_if<std::is_base_of<OverVoid, remove_all_pointers<_Ty>::type>::value>::type>
                                                                                                                       ^
..\src\helllo_world.cpp: In function 'int main()':
..\src\helllo_world.cpp:31:14: error: template argument 2 is invalid
  Move<Meta***> z;
              ^
..\src\helllo_world.cpp:32:13: error: template argument 2 is invalid
  Move<Meta**> w;
             ^
..\src\helllo_world.cpp:33:12: error: template argument 2 is invalid
  Move<Meta*> x;
            ^
..\src\helllo_world.cpp:34:11: error: template argument 2 is invalid
  Move<Meta> y;
           ^
..\src\helllo_world.cpp:31:16: warning: unused variable 'z' [-Wunused-variable]
  Move<Meta***> z;
                ^
..\src\helllo_world.cpp:32:15: warning: unused variable 'w' [-Wunused-variable]
  Move<Meta**> w;
               ^
..\src\helllo_world.cpp:33:14: warning: unused variable 'x' [-Wunused-variable]
  Move<Meta*> x;
              ^
..\src\helllo_world.cpp:34:13: warning: unused variable 'y' [-Wunused-variable]
  Move<Meta> y;
             ^

Are enums by default unsigned? [duplicate]

This question already has an answer here:

enum Color
 {
   GREY = 4294967294,
   RED 
 }

RED is assigned the largest value a 4 byte unsigned int can hold. When I use sizeof to know the size of my enum Color (sizeof (Color)), it prints 4. If I assign -1 to RED, the sizeof prints 8. Does that mean an enum is by default unsigned?

jeudi 30 juillet 2015

Why does CURLE_OPT_MALFORMAT occur when I do curl_easy_setopt(m_curl_handle, CURLOPT_URL, (char*)m_sUrl.c_str())?

I am curious why Alternative #1 functions okay while Alternative #2 returns CURLE_OPT_MALFORMAT when I do a curl_easy_perform(m_curl);

Alternative #1 curl_easy_reset(m_curl); char sUrl[8192]; /* In Alternative #1, m_strUrl is a C++ std::wstring member variable */ wcstombs(sUrl, m_sUrl.c_str(), m_sUrl.length()); sUrl[m_sUrl.length()] = '\0'; CURLcode code = curl_easy_setopt(m_curl, CURLOPT_URL, sUrl); CURLcode perform = curl_easy_perform(m_curl);

Alternative #2 curl_global_init(CURL_GLOBAL_ALL); /* init the curl session / m_curl_handle = curl_easy_init(); / set URL to get here*/ /* In Alternative #2, m_strUrl is a C++ std::string member variable */ CURLcode retval = curl_easy_setopt(m_curl_handle, CURLOPT_URL, (char *)m_sUrl.c_str()); CURLcode perform = curl_easy_perform(m_curl);

I read the following URL

How to convert a std::string to const char* or char*?

If you just want to pass a std::string to a function that needs const char* you can use std::string str; const char * c = str.c_str(); If you want to get a writable copy, like char *, you can do that with this: std::string str; char * writable = new char[str.size() + 1]; std::copy(str.begin(), str.end(), writable); writable[str.size()] = '\0'; // don't forget the terminating 0 // don't forget to free the string after finished using it delete[] writable; Edit: Notice that the above is not exception safe. If anything between the new call and the delete call throws, you will leak memory, as nothing will call delete for you automatically. There are two immediate ways to solve this.

** I am wondering why Alternative #2 chokes when I do :**

CURLcode retval = curl_easy_setopt(m_curl_handle, CURLOPT_URL, (char*)m_sUrl.c_str());

Is it necessary that I create a writable copy , like (char*) with std::string str; char * writable = new char[str.size() + 1]; std::copy(str.begin(), str.end(), writable); writable[str.size()] = '\0'; // don't forget the terminating 0

Any help is greatly appreciated

Make SFML Snake game more responsive to key presses?

I found a SFML C++ snake game and I've been messing around with it and changing a few things, but one of the things I can't figure out is how to make it more smooth/responsive with the arrow key presses. Right now it's using enum Direction {Up, Down, Left, Right}; with

while (window.isOpen())
{

    sf::Vector2f lastPosition(snakeBody[0].getPosition().x, snakeBody[0].getPosition().y);

    // Event
    sf::Event event;
    while (window.pollEvent(event))
    {
        //.....

        if (event.type == sf::Event::KeyPressed && event.key.code
                == sf::Keyboard::Return)
        {
            //clock.restart;
            if (!currentlyPlaying)
                currentlyPlaying = true;
            move = Down;

            New_Game(snakeBody, window_width, window_height, engine, apple, score, scoreText, lowBounds);
            mode = 1;
            moveClock.restart();
            //start game
        }
            if(inputClock.getElapsedTime().asSeconds() >= 0.07)
            {
                if(event.key.code == sf::Keyboard::Up && move != Down)
                    move = Up;
                inputClock.restart();
                if(event.key.code == sf::Keyboard::Down && move != Up)
                    move = Down;
                inputClock.restart();
                if(event.key.code == sf::Keyboard::Left && move != Right)
                    move = Left;
                inputClock.restart();
                if(event.key.code == sf::Keyboard::Right && move != Left)
                    move = Right;
                inputClock.restart();
            }
}

It's frustrating to play currently because I can't move as precisely as I would like. Is there a way to make the controls smoother or is it already responding to key presses as quickly as it's able to with my hardware?

Namespace qualified overloading of 'operator=='

I'm curious about why the following doesn't compile:

#include <iostream>
#include <functional>

namespace Bar {
struct Foo {
  int x;
};
}  // Namespace                                                                                                                     

static bool operator==(const Bar::Foo& a, const Bar::Foo& b) {
  return a.x == b.x;
}

int main() {
  Bar::Foo a = { 0 };
  Bar::Foo b = { 1 };

  // The following line is OK
  std::cout << (a == b) << std::endl;

  // The following line is not OK
  std::cout << std::equal_to<Bar::Foo>()(a, b) << std::endl;
}

The compiler barfs in this case:

[test]$ g++ --std=c++11 -o test test.cc
In file included from /usr/include/c++/4.8/string:48:0,
                 from /usr/include/c++/4.8/bits/locale_classes.h:40,
                 from /usr/include/c++/4.8/bits/ios_base.h:41,
                 from /usr/include/c++/4.8/ios:42,
                 from /usr/include/c++/4.8/ostream:38,
                 from /usr/include/c++/4.8/iostream:39,
                 from test.cc:1:
/usr/include/c++/4.8/bits/stl_function.h: In instantiation of ‘bool std::equal_to<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Bar::Foo]’:
test.cc:18:46:   required from here
/usr/include/c++/4.8/bits/stl_function.h:208:20: error: no match for ‘operator==’ (operand types are ‘const Bar::Foo’ and ‘const Bar::Foo’)
       { return __x == __y; }
                    ^
/usr/include/c++/4.8/bits/stl_function.h:208:20: note: candidates are:
...

The offending line doesn't compile even if I try another variant:

namespace Bar {
struct Foo {
  int x;
  bool operator==(const Foo& o) {
    return x == o.x;
  }
};
}  // Namespace

However, it seems like the following does compile:

namespace Bar {
struct Foo {
  int x;
};

static bool operator==(const Foo& a, const Foo& b) {
  return a.x == b.x;
}
}  // Namespace

What the heck is going on here?

Why can't we declare static variables in the class definition?

If I write code that looks like

#include <string>
class C {
  static const std::string MY_SPECIAL_STRING = "hi";
};

and I try to compile it, even in C++11 mode, g++ will complain:

static data member of type 'const std::string' must be initialized out of line

Why do we have this rule?


I mean, I can still kind of 'cheat' and have static variables inside static methods, e.g.:

#include <string>
class C {
  static const std::string& MY_SPECIAL_STRING() {
    static const std::string& ss("hi");
    return ss;
  }
};

This way, I don't need to put a declaration in a translation unit, and I effectively have the same thing, albeit with uglier syntax.

Proper syntax to assign std::vector to a specific memory location on the heap?

I am trying to implement the directions in these two SO posts regarding assigning containers to specific memory locations on the heap:

  1. Moving C++ objects, especially stl containers, to a specific memory location
  2. Create objects in pre-allocated memory

However, I must be doing something stupid (I'm new to C++) because I can't even get my code to compile (using C++ 11 as you can see below):

  std::vector<int> ints1 = {10, 20, 30};
  ints1.reserve(20);
  auto adr = &(*ints1.end());
  auto *ints2 = new(adr)(std::vector<int>(20);

I am getting an error of a expected , or ; before ) for the last line, which I take to mean that my syntax is just wrong, but how?

Also, once I fix this syntax, what's the best way to ensure these objects really are contiguous? I thought I would ensure that

&(*ints1.begin()) - &(*ints2.begin) is roughly on the order of sizeof(std::vector<int> v(20));

Is there a better way?

(p.s. I do realize I should allocate the memory I am going to use to do this to avoid undefined behavior)

C++ 11 Explicilty defaulted user defined destructor being treated as user defined?

Based on explanation given in Does deleting a copy constructor or copy assignment operator count as "user declared"?, I concluded that explicitly defaulted destructor would not stop generation of implicit move constructor. But on testing the following code using g++ 4.8.4, it confirms that move constructors are not being generated.

#include <iostream>
#include <string>

using namespace std;
class test
{
public:
    test():m_data("IrRest"){}
    string print(){return m_data;}
    ~test()=default;
private:
    string m_data;
};

int main(int argc, char** argv, char** arge)
{
    test t1;
    test t2(std::move(t1));
    cout<<"t1::data "; 
    cout<<t1.print()<<endl;

    cout<<"t2:data ";
    cout<<t2.print()<<endl;
    return 0;
}

Output of the above program is:

t1::data IrRest

t2:data IrRest

But my expectation was that t1 would have been moved to t2. Hence the output should have been:

t1::data 
t2:data IrRest

If I remove the d'tor completely, then I get the above expected output. This probably suggests that explicitly defaulted d'tor counts as user defined as opposed to the explanation given under the link mentioned at the beginning of this query. I would appreciate it someone can throw more light on the above.

time_point modulo duration does not compile

Env: win7, visual 2013 x64

Given a std::chrono::system_clock::time_point tp , and a std::chrono::system_clock::duration dur , how to find the next std::chrono::system_clock::time_point tp2 following :

 tp2 = tp - tp % dur + dur

This represents the next time point considering a clock and a heartbeat, for example dur=10s.

I tryied a lot ... my best I guess was this:

using namespace std; // for better readability

template < class duration_t >
system_clock::time_point next_time_aligned_on(const system_clock::time_point & tp, const duration_t & step)
{
    const system_clock::duration d = tp.time_since_epoch();
    const auto step2 = duration_cast<system_clock::duration>(step);

    const auto elapsed_since_last = d % step2;

    return tp - elapsed_since_last + step;      
} 

I got always the same compilation error:

1>C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC
\include\type_traits(1446): error C2446: ':' : no conversion from
'std::chrono::duration<std::chrono::system_clock::rep,std::chrono::system_clock::period>' 
to 'std::chrono::system_clock::rep'
1>          No user-defined-conversion operator available that can perform 
this conversion, or the operator cannot be called
1>          C:\trading\tepp\src\tepp/tools/strings.h(49) : see reference 
to class template instantiation std::common_type<std::chrono::system_clock::rep,std::chrono::duration<std::chrono::system_clock::rep,std::chrono::system_clock::period>>' 
being compiled
1>          st_gammalong.cpp(30) : see reference to function template 
instantiation 'std::chrono::system_clock::time_point  
tepp::next_time_aligned_on<std::chrono::seconds>(const std::chrono::system_clock::time_point &,const duration_t &)' 
being compiled
1>          with
1>          [
1>              duration_t=std::chrono::seconds
1>          ]

My question: how to use modulo operator in c++11 std::chrono ?

A const data member prevents automatic generation of both copy and move ctors?

Consider the following class:

struct A 
{ 
    int const x;
    A(int x) : x(x) { }  
}

Will this class get automatically generated move and copy ctors? Or is this prevented by the presence of the const field member x?

From my experience the answer is that move and copy ctors will not be generated, but I haven't found an explicit mention of this in the standard. Is there anything in the standard that implies that in this case the move and copy ctors are not generated?

Of course, the same questions apply to move/copy assignments.

How can I handle this variation?

Find Maximum sum in an array such that no 2 elements are adjacent. In this, 1 more condition was also there that first and last elements should also not be taken together.

If it would have been without the last condition, that is, then I developed the following code wherein I take two variables, incl and excl and find out the values. It is as follows:

#include <iostream>

using namespace std;

int main (void)
{
    int i,n;
    cin>>n;
    int arr[100];
    for ( i = 0; i < n; i++ )
        cin>>arr[i];
    int incl,excl,excls;
    incl = arr[0];
    for ( i = 1; i < n; i++ )
    {
        if (incl > excl)
            excls = incl;
        else
            excls = excl;
        incl = excl + arr[i];
        excl = excls;
    }
    if (incl > excl)
        cout<<incl;
    else
        cout<<excl;
    cout<<"\n";
    return 0;
}

How can I modify this for that special case? Thanks!

I try to serialize/deserialize std::unordered_map < int, std::unordered_set<int> > when I look at boost/serialization/map.hpp it seems to be simple (even tough I dont understand it quite) The following code seems to compile for serialization but fails for deserialization.

Does somebody know how to do this properly, or can point to some documentation of these STL serialization techniques? I have not found something unfortunately...

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <boost/serialization/map.hpp>
#include <boost/serialization/collections_save_imp.hpp>
#include <boost/serialization/collections_load_imp.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/serialization/split_free.hpp>

namespace boost { namespace serialization {

    template<class Archive, typename... TArgs >
        inline void save(Archive & ar, std::unordered_map<TArgs...> const&t, unsigned) {
            boost::serialization::stl::save_collection<Archive, std::unordered_map<TArgs...> >(ar, t);
        }

    template<class Archive, typename... TArgs >
        inline void load(Archive & ar, std::unordered_map<TArgs...> &t, unsigned) {
            boost::serialization::stl::load_collection<Archive,
                std::unordered_map<TArgs...>,
                boost::serialization::stl::archive_input_map<
                    Archive, std::unordered_map<TArgs...> >,
                boost::serialization::stl::no_reserve_imp<std::unordered_map<TArgs...> >
                    >(ar, t);
        }

    // split non-intrusive serialization function member into separate
    // non intrusive save/load member functions
    template <class Archive, typename... TArgs>
        inline void serialize(Archive & ar, std::unordered_map<TArgs...> &t, unsigned file_version) {
            boost::serialization::split_free(ar, t, file_version);
        }
} }


namespace boost { namespace serialization {

    template<class Archive, typename... TArgs >
        inline void save(Archive & ar, std::unordered_set<TArgs...> const&t, unsigned) {
            boost::serialization::stl::save_collection<Archive, std::unordered_set<TArgs...> >(ar, t);
        }

    template<class Archive, typename... TArgs >
        inline void load(Archive & ar, std::unordered_set<TArgs...> &t, unsigned) {
            boost::serialization::stl::load_collection<Archive,
                std::unordered_set<TArgs...>,
                boost::serialization::stl::archive_input_map<
                    Archive, std::unordered_set<TArgs...> >,
                boost::serialization::stl::no_reserve_imp<std::unordered_set<TArgs...> >
                    >(ar, t);
        }

    // split non-intrusive serialization function member into separate
    // non intrusive save/load member functions
    template <class Archive, typename... TArgs>
        inline void serialize(Archive & ar, std::unordered_set<TArgs...> &t, unsigned file_version) {
            boost::serialization::split_free(ar, t, file_version);
        }
} }


int main()
{

    std::stringstream ss;
    boost::archive::binary_oarchive oa2(ss, boost::archive::no_codecvt | boost::archive::no_header);

    std::unordered_map<int, std::unordered_set<int> > s, out;
    s.emplace( 0, std::unordered_set<int>{9,19} );

    oa2 << s;

    // Try to load this!!
    //boost::archive::binary_iarchive ia2(ss, boost::archive::no_codecvt | boost::archive::no_header);
    //ia2 >> out;
}

http://ift.tt/1DdrV6r

Assigning lambda to function reference variable [duplicate]

This question already has an answer here:

I'm quite proficient with C# but I'm new to C++ and I have really newbie question so please don't judge me rough

I have the following function pointer type:

typedef double (*PenaltyDelegate)(lifealgo *algo, int row, int col);

I thought that function pointer is the same thing as lambda independent of closure variables, but it turns out as soon as I specify variables that have to be catured or use one of generic capture modes, such as [=] or [&] the following assign stops working:

...

PenaltyDelegate penalty = [penalty_when_table_rows, penalty_when_table_cols, penalty_amount, penalty_when_table] (lifealgo *algo, int row, int col) -> double {
    auto index = 0;
    auto found = true;
    auto when_table = *penalty_when_table;

    for (int r = 0; found && r < penalty_when_table_rows; r++) {
        auto rr = r + row;

        for (int c = 0; found && c < penalty_when_table_cols; c++) {
            auto cell = 1 << algo->getcell(rr, col + c);
            auto when = when_table[index++];

            if ((cell & when) == 0) found = false;
        }
    }

    if (found) {
        return penalty_amount;
    } else {
        return 0.0;
    }
};

...

What is the reason for that to happen? Thank you in advance!

Why doesn't narrowing affect overload resolution?

Consider the following:

struct A {
    A(float ) { }
    A(int ) { }
};

int main() {
    A{1.1}; // error: ambiguous
}

This fails to compile with an error about an ambiguous overload of A::A. Both candidates are considered viable, because the requirement is simply:

Second, for F to be a viable function, there shall exist for each argument an implicit conversion sequence (13.3.3.1) that converts that argument to the corresponding parameter of F.

While there is an implicit conversion sequence from double to int, the A(int ) overload isn't actually viable (in the canonical, non-C++-standard sense) - that would involve a narrowing conversion and thus be ill-formed.

Why are narrowing conversions not considered in the process of determining viable candidates? Are there any other situations where an overload is considered ambiguous despite only one candidate being viable?

repeated extern declarations of qualified identifiers C++

Why is it that qualified names cannot be re-declared inside functions?

The following code fails to compile (in MSVC2015 and clang)

int i;

namespace N
{
int j;
}

void foo()
{
    extern int i;
    extern int i;
    extern int N::j;
    extern int N::j;
}

int main()
{
    return 0;
}

However, if we move the two lines extern int N::j; to just before void foo() then the code compiles fine. Note that repeated declarations of unqualified names do work.

How to prevent bounce in cocos2dx v3.7?

Game scence:

....
   auto edgeBody = PhysicsBody::createEdgeBox(winSize,PHYSICSBODY_MATERIAL_DEFAULT,3);
    auto edgeNode = Node::create();
    edgeNode->setPosition(winSize.width/2+origin.x , winSize.height/2+origin.y+10);
    edgeNode->setPhysicsBody(edgeBody);
....

Ball:

auto dinosaurBody = PhysicsBody::createCircle(dinosaurSprite->getContentSize().width/2);
dinosaurSprite->setPhysicsBody(dinosaurBody);

When ball collide with edge body it has bounce , how i remove it?

I have tried several ways of iterating over my "entries" map, but all of them produce the same lengthy error message.

dylan@Aspire-one:~$ g++ -std=c++11 dictionary.cpp
In file included from /usr/include/c++/4.8/map:60:0,
                 from dictionary.h:6,
                 from dictionary.cpp:1:
/usr/include/c++/4.8/bits/stl_tree.h: In instantiation of ‘void 
std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, 
_Alloc>::_M_insert_unique(_II, _II) [with _InputIterator = 
std::basic_string<char>; _Key = std::basic_string<char>; _Val = 
std::pair<const std::basic_string<char>, std::basic_string<char> >; 
_KeyOfValue = std::_Select1st<std::pair<const std::basic_string<char>, 
std::basic_string<char> > >; _Compare = std::less<std::basic_string<char> 
>; _Alloc = std::allocator<std::pair<const std::basic_string<char>, 
std::basic_string<char> > >]’:
/usr/include/c++/4.8/bits/stl_map.h:226:11:   required from 
‘std::map<_Key, _Tp, _Compare, _Alloc>::map(_InputIterator, 
_InputIterator) [with _InputIterator = std::basic_string<char>; _Key = 
std::basic_string<char>; _Tp = std::basic_string<char>; _Compare = 
std::less<std::basic_string<char> >; _Alloc = 
std::allocator<std::pair<const std::basic_string<char>, 
std::basic_string<char> > >]’
dictionary.h:11:66:   required from here
/usr/include/c++/4.8/bits/stl_tree.h:1721:28: error: no match for 
‘operator++’ (operand type is ‘std::basic_string<char>’)
for (; __first != __last; ++__first)
                        ^
/usr/include/c++/4.8/bits/stl_tree.h:1722:29: error: no match for 
‘operator*’ (operand type is ‘std::basic_string<char>’)
    _M_insert_unique_(end(), *__first);
                         ^
dylan@Aspire-one:~$

Here is my most recent code.

dictionary.cpp

#include "dictionary.h"
//I have included <string> <map> <iterator> "from dictionary.h"
bool dictionary::search_term(const std::string& term){
    std::map<std::string, std::string>::iterator it;
    for (it = entries.begin(); it != entries.end(); ++it){
        if(it->first != term);
        else return true;
    }return false;
}; 

So the error is in "dictionary.h"?

dictionary.h

#ifndef DICTIONARY_H
#define DICTIONARY_H

#include <iterator>
#include <string>
#include <map>

class dictionary{
    public:
        dictionary(const std::string& title, const std::string& definition = "")
            : entries(std::map<std::string, std::string>(title, definition)){;};
        bool write_entry(const std::string& term, const std::string& definition = "");
        bool define_term(const std::string& term, const std::string& definition);
        bool erase_entry(const std::string& term);
        bool search_term(const std::string& term);
    private:
        std::map<std::string, std::string> entries;
};

#endif//DICTIONARY_H

I tested the following code on Visual Studio and it compiles and prints "A(double)".

#include <iostream>
#include <initializer_list>

struct A {
    A(const std::initializer_list<int>&) { puts("initializer_list<int>"); }     // (1)
    A(const std::initializer_list<float>&) { puts("initializer_list<float>"); } // (2)
    A(double) { puts("A(double)"); }                                            // (3)
};

int main() {
    A var{ 1.1 };   
}

However both IntelliSense and http://ift.tt/1KBl1ug disagree, saying that more than one instance of constructor "A::A" matches the argument list (meaning both initializer-list constructors). Note that if either (1) or (2) is removed, code does not compile anymore, as "conversion from 'double' to 'float' requires a narrowing conversion".

Is this a bug? The behaviour feels inconsistent, but I see the same behaviour in VS13 and VS15 so maybe there is more to it?

But my real question is regarding the relevant section in standard.

3 List-initialization of an object or reference of type T is defined as follows:

  • ...
  • (3.5) — Otherwise, if T is a specialization of std::initializer_list, a prvalue initializer_list object is constructed as described below and used to initialize the object according to the rules for initialization of an object from a class of the same type (8.5).
  • (3.6) — Otherwise, if T is a class type, constructors are considered. ...

I don not understand (3.5), particularly the highlighted part - does it simply mean that type T has some initializer-list constructor?

vector accessing non zero elements but output as zero

I' did this program what suppose save pairs of string ,int on one vector and print the strings of the maximum number on vector but when i try to find this strings don't appears nothing so I try print all values of int's on vector and although was finding the maximum of 10 all values in the vector was printing as 0. Someone can explain was it occurred and how I can access the values , please.

#include <iostream>
#include <utility>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

typedef vector<pair<string,int>> vsi;

bool paircmp(const pair<string,int>& firste,const pair<string,int>&    seconde );

int main(int argc, char const *argv[]) {
 vsi v(10);

 string s;
 int n,t;

 cin>>t;

 for (size_t i = 0;i < t;i++) {
  for (size_t j = 0; j < 10; j++) {
   cin>>s>>n;
   v.push_back(make_pair(s,n));
  }
  sort(v.begin(),v.end(),paircmp);
  int ma=v[v.size()-1].second;
  cout<<ma<<endl;
  for (size_t j = 0; j < 10; j++) {
   cout << v.at(j).second  <<endl;
   if(v[j].second == ma)

   cout<<v[j].first<<endl;

  }

 }





return 0;
}

bool paircmp(const pair<string,int>& firste,const pair<string,int>& seconde ){
 return firste.second < seconde.second;
}

Efficient direct initialization of a std::vector

I have a struct, say

struct A {
  A(int n) : n(n) {}
  int n;
};

and I want to initialize a std::vector with some elements. I can do this by using an initialization list, or by emplacing the new elements:

// 3 ctors, 3 copy ctors, 3 dtors                                           
std::vector<A> v1{1, 2, 3};

// 3 ctors                                                                  
std::vector<A> v2;
v2.reserve(3);
v2.emplace_back(4);
v2.emplace_back(5);
v2.emplace_back(6);

As the comments show, the first version calls 3 constructors, 3 copy constructors, and 3 destructors. The version with emplace only uses 3 constructors.

Question: Can I do a direct initialization without the extra cost?

(Here's a longer version of the A struct that shows what's happening.)

How to pass this type auto function?

I'm trying to pass this auto function to another function, but apparently I can't pass an auto type, so can I change it to whatever the type actually is in order to pass it? By googling I read that you can use templates, but we didn't go over them in my class yet so I'd rather find a more beginner way of doing it if there is one.

std::uniform_int_distribution<int> yPosition(lowBounds, 23);    
auto randY = std::bind(yPosition, std::ref(engine));

void my_function(??? randY)
{
}

I am working on a program that prints a company information (e.g. company name, name of CEO etc.). I am using struct to group all the related variables. My struct looks like:

 struct Company
 {
      std::string NameOfCompany;     
      std::string NameOfCeo;
      int Revenue;
      int NumOfEmployees;
      std::string BranchesIn;
 };

I defined a void printInfo (Company x) to print information of a company. My main () takes data from user and passes that to printInfo(). Rest of the thing is done by printInfo (). My problem is with main () that is following:

   int main ()
  {
     using namespace std;
     Company x;
     cout << "Name of company: ";
     getline(cin, x.NameOfCompany);
     cout << "Name of CEO: ";
     getline(cin, x.NameOfCeo);
     cout << "Total Revenue: ";
     cin >> x.Revenue;
    cout << "Number of employees: ";
     cin >> x.NumOfEmployees;
     cout << "Branches In: ";
     getline(cin, x.BranchesIn);
     printInfo (x);
     return 0;
  }

The above code compiles and links fine (not including the void printInfo (), nothing wrong with that). On execution, the program starts from taking input for x.NameOfCompany. That's okay. But all the other getline () puzzled me. Program never asks for input for one (or both when i change the order of getlines, e.g. BranchesIn before NameOfCeo) variables which is set to take input through getline method. What's the problem. Does getline has any limitations?

If the code has any syntax or typographical error, please ignore. I swear that was linked and compiled fine.

Smart pointers' control block internal machinery

I'm wondering what are the exact conditions to release memory allocated for the internal control block shared by shared_ptr and weak_ptr.
I guess control block contains a shared_ptr counter and a weak_ptr counter.

#include <memory>
#include <iostream>

struct Dummy
{
    Dummy() { std::cout << "ctor" << std::endl; }
    ~Dummy() { std::cout << "dtor" << std::endl; }
};

int main()
{
    auto dummy = new Dummy();
    auto wp = std::weak_ptr<Dummy>(); // pointing to nothing

    {
        auto sp = std::shared_ptr<Dummy>(dummy); // 1
        wp = sp; // 2
    } // 3
    std::cout << "Land mark" << std::endl;
}

  1. Building a shared_ptr with dummy allocated memory. Control block is allocated, and it's Dummy pointer is set to "dummy"
  2. Building a weak_ptr from shared_ptr. Both smart pointers are sharing the same address of control block.
  3. Shared pointer is destroyed. Dummy dtor is called ("dtor" is printed before "Land mark"). Control block still lives until end of program.

Am I right about these comments ?
What happens (in details) within control block during these steps ?

Range-based for with brace-initializer over non-const values?

I am trying to iterate over a number of std::lists, sorting each of them. This is the naive approach:

#include<list>
using namespace std;
int main(void){
    list<int> a,b,c;
    for(auto& l:{a,b,c}) l.sort();
}

producing

aa.cpp:5:25: error: no matching member function for call to 'sort'
        for(auto& l:{a,b,c}) l.sort();
                             ~~^~~~
/usr/bin/../lib64/gcc/x86_64-linux-gnu/4.9/../../../../include/c++/4.9/bits/stl_list.h:1586:7: note: 
      candidate function not viable: 'this' argument has type 'const
      std::list<int, std::allocator<int> >', but method is not marked const
      sort();
      ^
/usr/bin/../lib64/gcc/x86_64-linux-gnu/4.9/../../../../include/c++/4.9/bits/stl_list.h:1596:9: note: 
      candidate function template not viable: requires 1 argument, but 0 were
      provided
        sort(_StrictWeakOrdering);
        ^
1 error generated.

Am I correctly guessing that brace-initializer is creating copy of those lists? And is there a way to not copy them, and make them modifiable inside the loop? (other than making list of pointers to them, which is my current workaround).

How do you enable VS2013 c++ compiler functionality?

So I'm pretty stumped here. I have a Library "A" that I wrote in C++ with VS2013, and can successfully include and build it within project "X".

Project "X" is an MFC app also developed in VS2013, and its Platform Toolset value is set to VS2013. It happens to be a Win32 application.

I now have to include the library in a different project "Y" (which was a VS2010 project, but I converted it using VS to 2013).

Project "Y" is NOT an MFC app, instead a .dll, and its Platform Toolset value is also set to VS2013. It is an x64 application.

However, when I try to build "Y", I get tons of compiler errors, mostly because the library uses C++11 features, and apparently VS isn't allowing it. The errors are mostly vector bracket-initialization syntax problems. E.G. non-aggregates cannot be initialized with initializer list.

But I don't understand. To my knowledge, VS2013 should support these features, and it appears to in my other projects. What could be the issue here? Is there something else I need to do to use the C++11-like compiler?

how can I prioritize a task and stop others on linux

I will have a linux service that waits messages from a central and let the tasks do that are ordered by those messages. I think to do is I need to create a new thread.

Moreover, one task would have an absolute priority compared to others and when the order for that task comes, I need to accomplish it as soon as possible. Also, since all these stuff is on embedded system and resources are restricted, I thought I need to pause all other threads that were created.

I imagine that I need some thing similar as here:

How to sleep or pause a PThread in c on Linux

But the question is not duplicate. I do not have exact point to pause threads. I need to pause them wherever possible, and continue when the prioritized task is finished.

And here it suggests a way that seems obsolete and also I could use std::thread.

How to pause a pthread ANY TIME I want?

  • How could I achieve prioritize one task?
  • (Maybe before that) To do tasks, do I need to design some thing like "Thread manager", or there could be simpler thoughts?

Note: I have used the word "task" as it is, not as a technical term.

This question already has an answer here:

I have pretty short question, why can't I declare a vector of string references, both

std::vector<std::string> strings;
std::vector<std::string*> strings;

declarations are working fine. But when I try to do the following:

std::vector<std::string &> strings;

I get a list of errors in std <vector> and <memory> header files...

Thank you in advance

mercredi 29 juillet 2015

merging sorted collection with map

I have n (let's say three) sorted key-value collections. The easiest way to merge them is to use std::map. Simple. However, because there are sorted, worth considering is to iterate through one collection and insert pair from the second collection in proper place, not using map::insert, which always will have O(n log n). So it seems to me that best for this situation will be using std::list with std::pair. I have also considered using std::vector with some maping keys on indexes and merging collections using new vector, however it will be more complicated.

Is this way of thinking have sense? Or is there any efficient way to use map in such task.

Thank You.

I am creating a program that scans and parses a text file, creates a database, and evaluates queries based on schemes and facts. My data structure is as follows:

Relation
    Scheme
    set<Tuple>

Where Scheme and Tuple inherit from std::vector<std::string>. The Scheme and every Tuple should have the same number of elements, and I repeatedly need to remove the values at a certain index in all three. For example, if I have:

Scheme
    C D H
Tuples
    EE200 F 10AM
    EE200 M 10AM
    EE200 W 1PM

organized so:

  C='EE200' D='F' H='10AM'
  C='EE200' D='M' H='10AM'
  C='EE200' D='W' H='1PM'

After removal at index 0 of every vector I should have:

  D='F' H='10AM'
  D='M' H='10AM'
  D='W' H='1PM'

I have written this code to localize the problem with an example. I first erase the index in the Scheme (which is essentially a vector of strings) and then loop through every Tuple in the set and attempt to remove the value at the index. In my example I forwent creating classes and instead just used std::string or std::vector<std::string>. The problem is here:

    for(set<vector<string>>::iterator t = tempTuples.begin(); t != tempTuples.end(); ++t)
    {
        // how do I erase the element at t?  
    }

Where tempTuples is the set of Tuple objects (here just vectors of strings). (*t).erase((*t).begin()) gives an error (no matching member function for call to 'erase') when inserted at this point. How do I remove the value at an index here?

multiple declarations in C++

In [basic.scope.declarative]p4, one reads

Given a set of declarations in a single declarative region, each of which specifies the same unqualified name, — (4.1) they shall all refer to the same entity …

A naïve reading might imply that the following code might be valid because "both declarations refer to the same entity"

int x;
int x;

One then might remember the one definition rule [basic.def.odr]p1. The above reasoning might apply only to declarations not to definitions. The distinction is spelled out in [basic.def]p2. For example, the following code is certainly valid:

extern int x;
extern int x;

The last example in [basic.def]p2 suggests then that the following code should be valid, but it does not compile (using MSVC2015).

struct B
{
    int y;
};

struct D : B
{
    using B::y;
    using B::y;
};

Where is the problem?


The error message is

the using-declaration for 'B::y' cannot co-exist with the existing using-declaration for 'B::y'

Pass lambda to numerical library

I am trying to use a numerical integration library that requires me to pass it a double (*f)(double,void*) as an argument. How can I pass it a lambda I create in the same scope? I tried

auto myLambda = [&](double d, void* data) { ... }

but the type of the lambda cannot be converted to the type required by the library. Is there an workaround?

Thank you for your time!

Here's my (mess of a) .pro file. I thought the problem may be here.

    TEMPLATE = app

QT += qml quick

SOURCES += main.cpp \
mysteamclass.cpp

RESOURCES += qml.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Default rules for deployment.
include(deployment.pri)

DISTFILES +=

HEADERS += \
mysteamclass.h
#--------------------------------ME= C++11 AND    LIBRARIES-----------------#

CONFIG+=c++11


INCLUDEPATH += /usr/local/include
INCLUDEPATH += /usr/local/freesteam

DEPENDPATH += /usr/local/include


 LIBS += -L/usr/local/include/

# LIBS += -L/usr/local/include -lgsl

# LIBS += -L/usr/local/include -libfreesteam
 LIBS += -L/usr/local/include -lgslcblas

LIBS+= -L/usr/lib/freesteam



win32:CONFIG(release, debug|release): LIBS += -L$$PWD/../../../../usr/lib/release/ -lfreesteam
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/../../../../usr/lib/debug/ -lfreesteam
else:unix: LIBS += -L$$PWD/../../../../usr/lib/ -lfreesteam

INCLUDEPATH += $$PWD/../../../../usr/include
DEPENDPATH += $$PWD/../../../../usr/include

Here's some code that's close to the #include, after following the error link on QtCreator.

    /* This is here only because every header file already includes this one.
   Get the definitions of all the appropriate `__stub_FUNCTION' symbols.
   <gnu/stubs.h> contains `#define __stub_FUNCTION' when FUNCTION is a stub
   that will always return failure (and set errno to ENOSYS).  */
#include <gnu/stubs.h>


#endif  /* features.h  */

Any thoughts on how (if) I could resolve this?

EDIT: Forgot to add that I'm using Linux Mint 17.2 x64.

How do I convert YYYY/MM/DD HH:MM:SS to std::chrono::system_clock::time_point?

I'm obtaining YYYY/MM/DD HH:MM:SS components from an offboard real time clock chip. I want to convert this to a std::chrono::system_clock::timepoint so that I may obtain the seconds since the Epoch and update the operating system's time.

I would like to use Howard Hinnant's proposed date library to perform this conversion.

I would intuitively do something like this:

date::year_month_day ymd = ...;
date::time_of_day tod = ...;
auto sysTime = date + tod;

but I don't see an appropriate operator+ overload for this. Am I missing something?

Another use case for this type of conversion is to convert a calendar date and time into a std::chrono::timepoint that I can pass to boost::asio::steady_timer.

Usage of members of a strongly typed enum in a function containing default arguments (VC++2015)

I am using G++ mostly and nowadays Visual Studio 2015. I wanted to build my project with VC++2015 but I get error messages that saying invalid use of '::' in a function given default arguments with a forward declared strongly typed enum.

Here is some code:

class Foo final
{
public:
    Foo() {}
    virtual ~Foo() {}

    //! Forward declaration of Bar
    enum class Bar : short;

    //! "Faulty" function with default argument
    void DoSmth(Bar aBar = Bar::Baz)
    {
        // ... code ...
    }

    //! Complete declaration of Bar
    enum class Bar : short
    {
        Baz
    };

protected:
private:
};

It gives me the error at the declaration of the function DoSmth() with the default argument Bar::Baz.

With G++ (tested with 4.9 and 5.1) the code compiles just fine but with VC++2015 it doesn't.

Im fully aware that I have to declare something before usage but. Is it just because that VC++2015 does not look within the scope of the class for the complete declaration and definition of Bar but G++ does? Or maybe does G++ just take the complete declaration and "merges" it with the forward declaration (as they are in the same scope) and thus makes it completely available to the class? Or maybe I am just plain wrong and something complete different causes this?

I can live with it that I have to change all my declarations for strongly typed enums in order to make it work with VC++2015.

But I also want to know why this is?

I am happy for all answers!

Visual Studio 2015 using a lambda in constexpr

So in the latest Visual Studio 2015 the following code seems to no longer work:

template<class F>
struct wrapper
{
    constexpr wrapper()
    {}
};

template<typename T> 
constexpr typename std::remove_reference<T>::type *addr(T&& t) 
{ 
    return &t; 
}

template<class F>
constexpr wrapper<F> wrap(F*)
{
    return wrapper<F>();
}


const constexpr auto add_one = wrap(true ? nullptr : addr([](int x)
{
    return x + 1;
}));

Visual Studio reports back illegal initialization of 'constexpr' entity with a non-constant expression. This used to work in the release candidate, but the latest build seems to no longer work(I am using version 14.0.23107.0). This should work(it does work in both clang and gcc).

Unfortunately, Microsoft doesn't let me report bugs. So does anyone know of a workaround?

Pure Virtual Destructor with Default Keyword

Is it possible to declare a destructor as pure virtual and use the default keyword? For example, I can't seem to make code like this work:

class MyClass
{
public:
  // Is there a way to combine pure virtual and default?
  virtual ~ MyClass() = 0,default;
};

One can of course later do:

MyClass::~ MyClass() = default;

Also, if the destructor is not pure virtual, the default keyword does work when it follows the declaration.

Check if expression is xvalue or prvalue [duplicate]

This question already has an answer here:

I just want to verify some rules described at cppreference. It is easy to check, whether expression is lvalue or rvalue.

#include <cassert>
#include <iostream>

template <typename T>
bool IsLValue(const char* i_expression, T&, bool i_expected = true)
  {
  assert(i_expected);
  std::cout << "l_value : " << i_expression << std::endl;
  return true;
  }

template <typename T>
bool IsLValue(const char* i_expression, T&&, bool i_expected = false)
  {
  assert(!i_expected);
  std::cout << "r_value : " << i_expression << std::endl;
  return false;
  }

int main()
  {
  int i = 10;
  int* p = &i;

  IsLValue("The name of a variable 'i'", i);
  IsLValue("The name of a variable 'p'", p);
  IsLValue("The name of a function 'main' in scope", main);
  IsLValue("The name of a function 'std::cout' in scope", std::cout);
  IsLValue("Built-in pre-increment '++i'", ++i);
  //etc
  return 0;
  }

Is there any way to check if expression is xvalue or prvalue?

Convert parent to child

I have class called AbsAlgorithm with three pure virtual functions like this:

class AbsAlgorithm
{
public:
    //...other methods
    virtual void run() = 0;
    virtual bool init(TestCase&) = 0;
    virtual void done() = 0;
};

This class is in my executable, called algatorc. End-user must create algatorc project and must also implement tis three methods. But the problem is this: he must also inherit TestCase class. which is parameter in init method. In my main program, I must compile code that user wrote, and build dynamic library and load it into my program. I did that. Problem is when I call init method. Example: User creates new algatorc project called Sorting. So he ends up with three classes: SortingTestSetIterator, SortingTestCaseand SortingAbsAlgorithm. In this SortingAbsAlgorithm he inverits AbsAlgorithm and implements pure virtual methods. In SortingTestCase he must inherit TestCase class and in SortingTestSetIterator he must inherit TestSetIterator and implement method called get_current(), which returns TestCase. My main program I loaded SortingTestSetIterator into TestSetIterator, like this:

create_it = (TestSetIterator* (*)())dlsym(handle, "create_iterator_object");
TestSetIterator *it = (TestSetIterator*)create_it();

So now, I can call methods like TestSetIterator::get_current() (this method returns pointer to TestCase, but user returns object of SortingTestCase). But when I call this method, as a result, I get TestCase. This is all ok, but then I need to pass this to AbsAlgorithm::init(...). Sure, still no problem, but when user implemented method init(...), he must convert this to child class (SortingTestCase). Is this posible? I know that this is trivial in Java, but I don't know how to do this in C++. Or is it a way that I define method TestCase* TestSetIterator::get_current() and then user somehow redefine this so that return type is SortingTestCase? Would this solve the problem?

Basically, problem is this: I have method SortingTestSetIterator::get_current() that returns pointer to instance of SortingTestCase class. So, is it somehow posible to convert parent to child?

Strategy to unit test move/copy constructors?

I want to write unit tests to test move/copy constructors/assigments of some classes I am writing. I want to make sure that the resources are handled appropriately, that a move ctor is called when I expect it to be called instead of a copy ctor, and vice-versa.

The problem is that I don't want to mess with the class code in order to test this. So, is there a way to know from the test code outside the class, when the move or the copy ctors/assignments were called?

What's a general strategy to unit-test copy/move ctors/assignments?

PD: I am using Catch unit-testing framework, so please provide an answer that can be implemented in Catch.

Sprite doesn't appear once I set its PhysicsBody [Cocos2d-X]

Directly copied and pasted from a issue I've sent on CC's GitHub page: Here's my piece of code: http://ift.tt/1IKeME9 (This is not EXACTLY the same whatsoever)

The "enemy" sprite doesn't appear if I set its PhysicsBody, the strange thing is that it happens only with that specific sprite.


No answers there so yeah, let's try it here.

C++11 constructor initializer with different syntaxes [duplicate]

This question already has an answer here:

I ended up on this page in the references.

I got somewhat confused with this example:

class X {
    int a, b, i, j;
public:
    const int& r;
    X(int i)
      : r(a) // initializes X::r to refer to X::a
      , b{i} // initializes X::b to the value of the parameter i
      , i(i) // initializes X::i to the value of the parameter i
      , j(this->i) // initializes X::j to the value of X::i
    { }
};

Is there any difference between using the bracketed initializer list syntax like b{x} and the traditional parenthesis syntax b(x)?

When should I use each one of them?

Linking boost.asio with C++11 enabled

I'm trying to build some program with g++ with -std=c++11 option. Program uses boost::asio.
I compiled it in windows with msvc1013 successfully.

But gcc 4.9.2 gives me a link error:

SomeFile.cpp:(.text+0x2c5): undefined reference to `boost::asio::ip::address::address(boost::asio::ip::address&&)'
SomeFile.cpp:(.text+0x2dc): undefined reference to `boost::asio::ip::address::address(boost::asio::ip::address&&)'

code whitch produce this error:

void someFunction(const QVarinat& value)
{
    .....
    boost::asio::ip::address adr = value.value<boost::asio::ip::address>();
    .....
}

I've tried to rebuild boost from sources with this command:

./bjam variant=release link=static runtime-link=shared toolset=gcc cxxflags="-std=c++11" 

c++ reading with cin using previously read variable immediately

somewhere in my code for some online judge I have the following:

vector<int> arr(1 << 20);

int p;
cin >> p >> arr[p];

this gives me a segmentation fault when compiled with judge's (I don't have access to their machine though) compiler g++ 4.9.2 but not on my local Apple LLVM version 6.0 (clang-600.0.57)

however writing it as:

int p;
cin >> p;
cin >> arr[p];

works fine on the judge as well. Is this a known thing/bug? And why doesn't the first version work as expected?

cannot convert 'const ScalarMultipleReturnType Error

Running my code gives the following compilation error:

cannot convert 'const ScalarMultipleReturnType {aka const Eigen::CwiseUnaryOp, const Eigen::Matrix >}' to 'double' in initialization double tempSum = deltaT*(vectorB(i)-vectorB2(i))*k[i];

at the following line:

double tempSum = deltaT*(vectorB(i)-vectorB2(i))*k[i];
truncError = truncError + tempSum;

I have defined variables vectorB and vectorB2 as: Eigen::VectorXd vectorB; and initialized as vectorB = Eigen::VectorXd::Zero(size); for both vectors respectively.

k is defined as: std::vector<Eigen::MatrixXd> k(size);

deltaT is of type double

Each Even though k is a vector of Matrices, each matrix has only one value. eg: k[0] is a single double value.

Can someone please help me with the type conversion here? I think that's what's causing the issue. I wish to convert the RHS of the expression double tempSum = deltaT*(vectorB(i)-vectorB2(i))*k[i] into a double variable.

What smart pointers should I use in Qt C++11 project?

I've read this great question:

What C++ Smart Pointer Implementations are available?

and now my question is the following: I have Qt project supporting C++11, what smart pointers I may need? I feel like I may need std::unique_ptr and QSharedPointer - is it OK to mix pointers of different types, standard library and Qt in one project?

Or how can I replace std::unique_ptr by Qt means?

How can I check if my string contains garbage characters

I have a function which receives a wchar_t string as an input. Due to this function being potentially called from several places, it can contain valid information, be empty, or might contain garbage characters.

It has then to be copied using _tcscpy_s.

Unfortunately, this will break if the incoming whcar_t string has garbage characters.

Is there any way to detect if information in the string is garbage, i.e., invalid Unicode characters?

Are multiple non-type template parameter packs allowed?

[temp.param] p11 says (in N4527):

(...) A template parameter pack of a function template shall not be followed by another template parameter unless that template parameter can be deduced from the parameter-type-list of the function template or has a default argument

In the context of non-type template parameter packs, there can't be default arguments,
so what exactly needs to be deduced for the packs (just the type, or the values, too)?

i.e. I'm wondering if this is allowed by the standard (C++11, 14 or 1z):

template<typename T, T... A, T... B>
void foo(T) {}

The first pack's values could be explicitly specified, but the second pack is "unreachable" and would always be empty if I'm not mistaken.

clang++-3.6 and g++-5.2 seem to accept these empty unreachable packs (even non non-type packs), but VC++ 14.0 refuses them with the error:

error C3547: template parameter 'B' cannot be used because it follows a template parameter pack and cannot be deduced from the function parameters of 'foo'

Proper syntax to use std::map access operator [] via std::unique_ptr

My question is really simple. I googled a lot, but somehow I cannot figure it out. I use a C++ std::map with a std::unique_pointer like this:

std::unique_ptr<std::map<int,std::string>> my_map( new std::map<int,std::string>());

Now, I want to use the access operator [] of the map. But I always get a compiler error.

my_map[1] = "XYZ";    // error C2676
my_map->[1] = "XYZ";  // error C2059

Without the std::unique_ptr, my code would be like this, and it works. But how do I do the same via std::unique_ptr? Please help me.

std::map<int,std::string> my_map;
my_map[1] = "XYZ";   // OK!

Modern C++ is welcome and even desired.

Why are non-integral non-type template parameters illegal?

One can have constant expressions of non-integral literal types:

constexpr double a = 4.5;

What is the reason for not allowing non-type template parameters of such types? In other words, why shouldn't I be able to write:

template <double param>
struct C {...};

Can a program exist that is valid in C++14 but invalid in C++11?

C++14 is intended as a small upgrade to C++11 mainly involved in cleaning up bugs and making small, low impact, improvements. But my question is that are there any programs which are valid in C++14 but invalid in C++11?

how to know if threads uses all cores android

On an Android NDK application, I'm using several threads, with c++11 threads. I think all threads are using only one of the 4 cores on my device, because the cpu usage percentage sums up to only 74%.

While running my app, I profile using top with the "showing threads" option:

top -t | grep "com.myapp"

31015  9824  1   9% R 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015  9821  1   9% R 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015  9819  0   9% R 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015  9826  2   9% S 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015  9823  2   9% R 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015 31015  0   8% R 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015  9822  1   7% S 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015  9820  1   7% S 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015  9825  2   4% R 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015  9493  1   3% S 1697312K 421060K  fg u0_a742  Thread-1068     com.myapp
31015  9497  1   0% S 1697312K 421060K  fg u0_a742  GL updater      com.myapp
31015  9793  0   0% S 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015  9495  0   0% S 1697312K 421060K  fg u0_a742  GL updater      com.myapp
31015 31268  1   0% S 1697312K 421060K  fg u0_a742  Thread-1061     com.myapp
31015 31016  2   0% S 1697312K 421060K  fg u0_a742  GC              com.myapp
31015 31017  0   0% S 1697312K 421060K  fg u0_a742  Signal Catcher  com.myapp
31015 31018  0   0% S 1697312K 421060K  fg u0_a742  JDWP            com.myapp
31015 31019  0   0% S 1697312K 421060K  fg u0_a742  Compiler        com.myapp
31015 31021  3   0% S 1697312K 421060K  fg u0_a742  ReferenceQueueD com.myapp
31015 31022  2   0% S 1697312K 421060K  fg u0_a742  FinalizerDaemon com.myapp
31015 31023  0   0% S 1697312K 421060K  fg u0_a742  FinalizerWatchd com.myapp
31015 31026  0   0% S 1697312K 421060K  fg u0_a742  Binder_1        com.myapp
31015 31027  3   0% S 1697312K 421060K  fg u0_a742  Binder_2        com.myapp
31015 31188  1   0% S 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015 31189  2   0% S 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015 31190  1   0% S 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015 31191  2   0% S 1697312K 421060K  fg u0_a742  com.myapp       com.myapp
31015 31254  2   0% S 1697312K 421060K  fg u0_a742  Binder_2        com.myapp
31015 31255  0   0% S 1697312K 421060K  fg u0_a742  Binder_2        com.myapp
31015 31256  1   0% S 1697312K 421060K  fg u0_a742  Binder_2        com.myapp
31015 31260  2   0% S 1697312K 421060K  fg u0_a742  Binder_3        com.myapp
31015 31261  3   0% S 1697312K 421060K  fg u0_a742  Binder_4        com.myapp
31015 31270  3   0% S 1697312K 421060K  fg u0_a742  FileObserver    com.myapp
31015 31337  2   0% S 1697312K 421060K  fg u0_a742  Binder_5        com.myapp

I calculate the number of threads to use with a Maximum of android_getCpuCount() from cpufeatures.h on NDK, And it adds the top most 9 threads.

How can I know if all the cores are in use ? (Pressing "1" option is not included in the android's top application.)

And if I'm using only one core, as I suspect, how can I make the threads use multiple cores ?