mercredi 31 août 2016

std::string& vs boost::string_ref

Does it matter anymore if I use boost::string_ref over std::string& ? I mean, is it really more efficient to use boost::string_ref over the std version when you are processing strings ? I don't really get the explanation offered here: http://ift.tt/2bLejEC . What really confuses me is the fact that std::string is also a handle class that only points to the allocated memory, and since c++11, with move semantics the copy operations noted in the article above are not going to happen. So, which one is more efficient ?

How to iterate and get values from a json file shown using rapidjson

In the below code I have array of objects. I need to iterate over them and get their values.Please help.

Json File :

<pre>   
   [ 
   { 
      "condition":"Abdominal Distension",
      "meds":[  
         {  
            "genericName":"Bethanechol",
            "tradeNames":
            [  
               "Bethacol",
               "Betheran (25 mg)"
            ]
         },
         {  
            "genericName":"Pamabrom",
            "tradeNames":
            [  
               "Spasmonova (10mg/25mg/325mg)"
            ]
         }
      ]
   },
   {  
      "condition":"Alcohol abuse",
      "meds":[  
         {  
            "genericName":"Acamprosate",
            "tradeNames":
            [  
               "Acamprol tab",
               "Acamptass (333 mg)",
               "Acmacal tab"
            ]
         },
         {  
            "genericName":"Chlordiazepoxide",
            "tradeNames":
            [  
               "Anxizide",
               "Anxizide",
            ]
         }
      ]
   }
]
</pre>

Ignore Please : The post asks me to add something. But I don't know what to add.So. Again it says "It looks like your post is mostly code;Please add some more details." Oh God! I don't know what to add at all.Could You stop this please.

Placement new plus destructor and simple value initialization semantic

Can one assume in unevaluated context, that (::new (std::declval< void * >()) T())->~T() is semantically full equivalent to simple T()? Assume neither global, nor class-scope operator new are not overloaded, if it mutters much.

Often in type traits T() used inside operator noexcept() to determine whether only the separate constructor is noexcept or not. Surely it is wrong.

To prevent the loss of generality one can assume that T() here is either a calling of a default constructor or of any other constructor.

arm-none-eabi 4.8/4.9 cross compiler throws error for std::Promise: error "has incomplete type and cannot be defined"

Am trying to build a sample code shared in below link http://ift.tt/1Jpe13R

with cross compiler as mentioned which is 4.9.3 and get the error for std::promise as "has incomplete type and cannot be defined"

*C:\>arm-none-eabi-g++.exe -std=c++11 -lpthread t
est.cpp
test.cpp: In function 'void accumulate(std::vector<int>::iterator, std::vector<i
nt>::iterator, std::promise<int>)':
test.cpp:9:35: error: 'accumulate_promise' has incomplete type
                 std::promise<int> accumulate_promise)
                                   ^
In file included from test.cpp:3:0:
c:\users\h191340\desktop\arm4.9\arm-none-eabi\include\c++\4.9.3\future:123:11: e
rror: declaration of 'class std::promise<int>'
     class promise;
           ^
test.cpp: In function 'int main()':
test.cpp:18:23: error: aggregate 'std::promise<int> accumulate_promise' has inco
mplete type and cannot be defined
     std::promise<int> accumulate_promise;
                       ^
test.cpp:19:22: error: variable 'std::future<int> accumulate_future' has initial
izer but incomplete type
     std::future<int> accumulate_future = accumulate_promise.get_future();
                      ^
test.cpp:20:5: error: 'thread' is not a member of 'std'
     std::thread work_thread(accumulate, numbers.begin(), numbers.end(),
     ^
test.cpp:24:5: error: 'work_thread' was not declared in this scope
     work_thread.join();  // wait for thread completion
     ^*

I am unable to delete one of the key from map successfully in c++

I have a map in the following format -

map<int, vector<int>> myGraph;

I am trying to delete a key from myGraph using -

myGraph.erase(firstValue);

Here firstValue is key from myGraph.

The value of corresponding to firstValue key is getting deleted but the key still exists in the map.

int main(void) {
    string name;
    map<int, vector<int>> myGraph;
    int temp, value;
    while(getline(cin, name)) {
        stringstream stream(name);
        stream >> value;
        while(stream >> temp) {
            myGraph[value].push_back(temp);
        }
    }
        while(myGraph.size() > 2) {
            auto iter = myGraph.begin();
            advance(iter, rand() % myGraph.size());
            auto mik = iter->second.begin();
            cout << iter->second.size() << " " << iter->first<< endl;
            advance(mik, rand() % iter->second.size());
            int firstValue = iter->first, secondValue = *mik;
            myGraph[secondValue].insert(myGraph[secondValue].end(), iter->second.begin(), iter->second.end());
            myGraph.erase(firstValue);
            myGraph[secondValue].erase(remove(myGraph[secondValue].begin(), myGraph[secondValue].end(), firstValue), myGraph[secondValue].end());
            for(auto iterate = myGraph.begin(); iterate != myGraph.end(); iterate++) {
                replace(iterate->second.begin(), iterate->second.end(), firstValue, secondValue);
            }
        }

    cout << myGraph.size() << endl;
    return 0;
}

C++ pointers in Cython

I use Cython to wrap my C++ classes. Some of methods return sth. like class_name*. class_name may be some complicated class already described in pxd and pyx file (like it is mentioned here in extended answer http://ift.tt/2bCxfbz). But Cython says in pyx defs that I am returning not a Python type. I want to be able to return c++-like pointers in python and then use methods of this objects and to pass them to c++ methods.

Is implementing RAII via constructors and destructors considered bad 'Modern C++'?

With the advent of smart pointer in C++, is manually implementing RAII via constructors and destructors considered bad 'modern C++' practice? Or are there applications where this is still relevant?

Is it possible to get reference to 'this' pointer in class body without using the class name?

Here is what I tried:

class i_really_dont_wanna_to_use_this_class_name_for_reference_type_of_this
{
    //get this:
    auto get_this() -> decltype(this) {return this;}

    //now, somehow declare reference do value returned by get_this()
    //here is what I tried but failed
    auto * const & this_ref = get_this(); //error, invalid use of auto
    decltype(this)& this_ref = get_this() //error, invalid use of this     
}

Is it even possible?

Why does a std::string object passed to a template function not prefer std::string overload?

I'm writing a program and I want to be able to cleanly wrap a string in quotes without having to do something like

std::string firstString = "This is a string";
std::string myString = "\"" + firstString + "\"";    

So I wrote a couple of template functions to take their arguments and wrap them in quotes. I've also included my first (naive) attempt at writing a general toString() function (I know about to_string, but I'm doing this for learning too).

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <typeinfo>

template <typename T>
std::string toString(const T &convert)
{
    std::string returnString{""};
    std::stringstream transfer;
    transfer << convert;
    transfer >> returnString;
    return returnString;
}

template<typename T>
std::string tQuoted(const T &convert)
{
    std::cout << "Called template overload" << std::endl;
    return ("\"" + toString(convert) + "\"");
}

template<typename T>
std::string tQuoted(const std::string &convert)
{
    std::cout << "Called std::string overload" << std::endl;
    return ("\"" + convert + "\"");
}

template<typename T>
std::string tQuoted(const char *convert)
{
    std::cout << "Called const char overload" << std::endl;
    return ("\"" + static_cast<std::string>(convert) + "\"");
}

template<typename T>
std::string tQuoted(std::string convert)
{
    std::cout << "Called normal std::string overload" << std::endl;
    return ("\"" + convert + "\"");
}

template<typename T>
std::string tQuoted(std::string&& convert)
{
    std::cout << "Called rvalue std::string overload" << std::endl;
    return ("\"" + convert + "\"");
}

int main()
{
    std::vector<std::string> my{"Hello", "30 Days Of Coding", "All Work And No Play"};

    std::string myString = "Hello, World!";
    std::string *strPtr = &myString;
    std::string *mySuperPtr = new std::string{"He's a cockaroach"};

    for (std::vector<std::string>::const_iterator iter = my.begin(); iter != my.end(); iter++) {
        std::cout << tQuoted(*iter) << std::endl;
    }

    std::cout << tQuoted(myString) << std::endl;
    std::cout << tQuoted(*strPtr) << std::endl;
    std::cout << tQuoted(mySuperPtr) << std::endl;
    std::cout << tQuoted(std::string{"Another string"}) << std::endl;

    delete mySuperPtr;
    mySuperPtr = nullptr;

    return 0;

}

Every one of those calls the template constructor:

Called template overload
"Hello"
Called template overload
"30"
Called template overload
"All"
Called template overload
"Hello,"
Called template overload
"Hello,"
Called template overload
"0x13cad10"
Called template overload
"Another"

Of course, a much less naive toString() method would do basic checking to see if the parameter was a std::string, and just return that if it was. It seems that a std::stringstream will stop when it encounters the first space in a string (hence the truncated output). However, this isn't the main focus of my confusion.

Sorry for the very basic question, but this one really has me stumped. Thanks for any help you can provide.

Is offsetof dereferencing a null pointer [duplicate]

This question already has an answer here:

In looking at how my compiler (VS2015) implements the offsetof macro, I see the following implementation:

#define offsetof(s,m) ((size_t)&reinterpret_cast<char const volatile&>((((s*)0)->m)))

It appears to me that this is dereferencing a null pointer at ((s*)0)->m. I understand this to be undefined behavior. Is this undefined behavior that the compiler specifies more strongly than the language, or is there some nuance to the "never dereference a null pointer" rule that I don't understand?

How to resolve symbols after statically linking to Visual C++ Runtime? [duplicate]

I have a little command line project which makes use of the jpeglib from the jpeg group and I want to statically link to the VC++ Runtime so I can distribute my executable more easily.

I found numerous posts explaining that you have to set:

Project Properties -> Configuration Properties -> C/C++ -> Code Generation -> Runtime Library

to /MT

But this gives me several unresolved symbols.

47 Errors in Debug mode
5 Errors in Release mode

1>jpeg.lib(jdatasrc.obj) : error LNK2001: Unresolved External Symbol "__imp__fread".
1>jpeg.lib(jdatadst.obj) : error LNK2001: Unresolved External Symbol "__imp__ferror".
1>jpeg.lib(jmemmgr.obj) : error LNK2001: Unresolved External Symbol "__imp____stdio_common_vsscanf".
1>jpeg.lib(jdmarker.obj) : error LNK2001: Unresolved External Symbol "__imp__strncpy".
1>MSVCRT.lib(_chandler4gs_.obj) : error LNK2001: Unresolved External Symbol "__except_handler4_common".

I dont know what to do. Help is much appreciated!

C++ std::array wrapper for Cython

I use Cython to wrap my C++ classes. Some of methods return sth. like std::array<class_name, 2>. My code looks like extended example from here: http://ift.tt/2bCxfbz. But I don't see a way to tell Cython to automatically convert this to Python's list. When class_name is a simple type (like int), that should be pretty easy. But I also want to be able to use it with complicated C++ classes (for which I created cython cdefs in pxd file and python defs in pyx file)

I know a workaround: in my original C++ code to create methods that return vectors instead of arrays, but that looks ugly and doesn't solve the second problem.

Data is not being written properly, while Writing an object to a file in c++

I have created 2 classes , One which creates the object and another which saves the object to a file.

The file is being created properly , but when i read the file directly from the location , it has junk values in it

Is it because iam type casting the object to char*, what should be the right way?

class custFile {
public :
 void append(myCust a)
 {
    myObj.open("/Users/tejas/Documents/cust.txt",std::ios::app);
    myObj.seekp(0,ios::end);
    myObj.write( (char *) &a ,  sizeof(myCust));
    myObj.close();
 }

} ;

class myCust {
public:
  void getdata(){
      std::cout<<"Enter Acno , CName,bal \n" ;
      std::cin>>acno>>cname>>bal;
  }
};

int main(int argc, const char * argv[]) {
  myCust custObj;
  custObj.getdata();
  custFile obj;
  obj.append(custObj);  
}

The Input is

123 Peter 10000

Below is the data in the file

{^@^@^@[Peter^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@~»F

PS: I have nt included the header files here Thanks

Workaround for passing variadic arguments to lambda expression if compiler does not support it

I have two solutions, both work as I expect but the first one works only with newer version of GCC (5.2.1 for sure) and the second one works in GCC >= 4.8.3. The problem is that at my work I unfortunately do not have access to newer version of GCC.

The first solution is basically what I wanted by the behavior and by the level of complexity. The second one also works but this is the ugliest thing I have ever written and to be honest I do not know if this is the correct code (but it works).

Ok, firstly I will describe the problem that I am facing: I have a function called logic() here, which takes callable object to invoke some additional logic among other instructions. These instructions of course are not here, because they are not necessary, they are marked as (X).

template <typename C>
void logic (C c) {
    // before callable actions (X)
    c ();
    // after callable actions (X)
}

What I want to do as the callable object is to set some bool value(s) using appropriate type(s) - set_single() function. For the example I will use some additional types:

struct P1 {};
struct P2 {};
struct P3 {};

Consider first solution:

namespace Solution1 {

template <typename T>
void set_single (bool c) {
    // use type T to set c value - details are not the case here.

    std::cout << "value = " << c << std::endl;
    std::cout << "P1 = " << std::is_same<T, P1>::value << std::endl;
    std::cout << "P2 = " << std::is_same<T, P2>::value << std::endl;
    std::cout << "P3 = " << std::is_same<T, P3>::value << std::endl;
}

template <typename T, typename K, typename... Ts, typename... Vs>
void set_single (bool t, bool k, Vs&&... args) {
    set_single<T> (t);
    set_single<K, Ts...> (k, std::forward<Vs> (args)...);
}

template <typename... Ts, typename... Args>
void set (Args&&... args) {
    static_assert (sizeof... (Ts) == sizeof... (Args), "");

    logic ([&] () {
        set_single<Ts...> (std::forward<Args> (args)...);
    });
}

}

set() function is a wrapper and it is public for the user, set_single() are implementation details so they are hidden (for simplicity they are not written in a class).

So, passing callable object to logic() function inside set() function I invoke set_single() function arbitrary number of times passing all the values with corresponding types that I need. So, for example, usage could be like this:

Solution1::set<P1, P2, P3> (true, false, true);

and this will use type P1 to set true, type P2 to set false and type P3 to set true.

So, here we have a solution when your compiler does not support passing variadic arguments to lambda expression.

namespace Solution2 {

template <typename... Ts>
struct X {
    X () = default;
    X (Ts... t) : tup {std::make_tuple (t...)} {}
    std::tuple<Ts...> tup;
};

template <int...>
struct Ints {};

template <int N, int... Is>
struct Int_seq : Int_seq<N-1, N, Is...> {};

template <int... Is>
struct Int_seq<0, Is...> {
    using type = Ints<0, Is...>;
};

template <int... Is>
using Iseq = typename Int_seq<Is...>::type;

template <int I, typename... Args, typename... Types>
void set_single (Ints<I>, const std::tuple<Args...>& a, const std::tuple<Types...>& t) {
    std::cout << "value = " << std::get<I> (a) << std::endl;
    auto p1 = std::get<I> (t);
    auto p2 = std::get<I> (t);
    auto p3 = std::get<I> (t);
    std::cout << "P1 = " << std::is_same<P1, decltype (p1)>::value << std::endl;
    std::cout << "P2 = " << std::is_same<P2, decltype (p2)>::value << std::endl;
    std::cout << "P3 = " << std::is_same<P3, decltype (p3)>::value << std::endl;
}

template <int I, int K, int... Is, typename... Args, typename... Types>
void set_single (Ints<I, K, Is...>, const std::tuple<Args...>& a, const std::tuple<Types...>& t) {
    set_single (Ints<I> {}, a, t);
    set_single (Ints<K, Is...> {}, a, t);
}

template <typename... Ts, typename... Args>
void set (Args... args) {
    static_assert (sizeof... (Ts) == sizeof... (Args), "");

    X<Ts...> types {};
    X<Args...> arguments {args...};

    logic ([&types, &arguments] () {
        set_single (Iseq<std::tuple_size<decltype (arguments.tup)>::value-1> {}, arguments.tup, types.tup);
    });

}

}

I used type Solution2::X to store values and types. I tried to do some std::bind() stuff, but it was painful, so I used some integer sequence (which probably implementation is rather poor). Like I said, both solutions work but the second one is not so cool like the first one.

Could any of you tell me if Solution2 can be replaced by some kind of easier solution? I am pretty sure that some exists.

And usage with output looks like:

Solution1::set<P1, P2, P3> (true, false, true);

value = 1
P1 = 1
P2 = 0
P3 = 0
value = 0
P1 = 0
P2 = 1
P3 = 0
value = 1
P1 = 0
P2 = 0
P3 = 1


Solution2::set<P1, P2, P3> (true, false, true);

value = 1
P1 = 1
P2 = 0
P3 = 0
value = 0
P1 = 0
P2 = 1
P3 = 0
value = 1
P1 = 0
P2 = 0
P3 = 1

Data race in C++

struct S {
int a;
int b;
};

Size of L1 cache line is equal 64B.

global S s;
Thread1:
s.a = 2;

Thread2: 
s.b = 1;

Is it a data race in C++?

Using the value that any_of finds to use in a return outside lambda

A working piece of code:

std::vector<double>::iterator it = std::find_if(intersections.begin(), intersections.end(), [&](const double i) {return i >= 0;});
if (it != intersections.end())
    return rayOrigin + *(it) * rayDirection);

But I would like to use something like this

Is there a way to capture the i in a clean way (not using a temp variable), that the any_of finds here to use it in the return statement

if (std::any_of(intersections.begin(), intersections.end(), [&](const double i) {return i >= 0;}))
    return rayOrigin + i * rayDirection);

what is the difference between emplace and insert in vector C++?

Although there are posts related to the same questions I could not find satisfactory answer of whats the exact difference between insert and emplace since I feel both do similar things except for emplace which cannot fill the range of elements into a vector. Can someone explain me if there are anymore differences?

initialization order of static const initialized with functions

In short, I need to initialize a const static member with some value obtained from a file and keep it thereby same for every object derived from it.

So let's say I've a program -

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

class A
{
public:
static const int VAL1;
static const int VAL2;
};

int F(const std::string);

const int A::VAL1 = F("1.txt");
const int A::VAL2 = F("2.txt");

int F(const std::string filename)
{
  std::ifstream file(filename);
  int result = 0;
  file >> result;
  return result;
}

int main () {
  std::cout << A::VAL1 << " " << A::VAL2 << "\n";
}

Is it guaranteed that static members will be always initialized before creation of objects, because that's what I want :/

visual studio code is not autocompleting std:: in c++ on ubuntu

The behaviour i am looking for is when i type

using std::co then i expect it to autocomplete to cout (or at least suggest)

using std::vect then i expect it to autocomplete to vector

I have it set up on my laptop and it works perfectly fine ... it is just on my main vm that it does not. Sadly after a few hours of tinkering and googling not figured it out.

installed c++, build essentials, clang-format-3.8 vscode, c++ extention and c++ autocomplete. noticed the one that worked had this added to the c_cpp_properties (not that i expected clang to help but was out of other options.)

,
    "clang_format" : {
        "style" : "file",
        "fallback-style" : "LLVM",
        "sort-includes" : false
    }

I think it is probably a package difference but cannot see where that difference is. I also cannot find the difference in vscode config if there is one.

g++ can't find "_gladLoadGL"

I am following this tutorial, and I am using glad to load OpenGL. I managed to generate a loader using the web-service and I am compling my code like this:

g++ tutorial.cpp  -o exec -std=c++11 -lglfw3 -framework Cocoa -framework IOKit -framework CoreVideo

and this is what I get:

Undefined symbols for architecture x86_64:
  "_gladLoadGL", referenced from:
      _main in glfw_tutorial-64e053.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Here is my code:

#include "glad/glad.h"
#include <GLFW/glfw3.h>
#include "linmath.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

static const struct{
  float x,y;
  float r,g,b;
}vertices[3] = {
  { -0.6f, -0.4f, 1.f, 0.f, 0.f },
  {  0.6f, -0.4f, 0.f, 1.f, 0.f },
  {  0.f, 0.6f, 0.f, 0.f, 1.f }
};

static const char* vertex_shader_text =
"uniform mat4 MVP;\n"
"attribute vec3 vCol;\n"
"attribute vec2 vPos;\n"
"varying vec3 color;\n"
"void main()\n"
"{\n"
"    gl_Position = MVP * vec4(vPos, 0.0, 1.0);\n"
"    color = vCol;\n"
"}\n";

static const char* fragment_shader_text =
"varying vec3 color;\n"
"void main()\n"
"{\n"
"    gl_FragColor = vec4(color, 1.0);\n"
"}\n";

static void error_callback(int error, const char* description)
{
    fprintf(stderr, "Error: %s\n", description);
}

static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GLFW_TRUE);
}

int main(void){
  GLFWwindow* window;
  GLuint vertex_buffer, vertex_shader, fragment_shaer, program;
  GLint mvp_location, vpos_location, vcol_location;

  glfwSetErrorCallback(error_callback);

  if (!glfwInit())
    exit(EXIT_FAILURE);

  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

  window = glfwCreateWindow(600, 600, "First Graphics Program", NULL, NULL);

  if(!window){
      glfwTerminate();
      exit(EXIT_FAILURE);
  }

  glfwSetKeyCallback(window, key_callback);
  glfwMakeContextCurrent(window);
  if (!gladLoadGL()) {
    std::cout << "Failed to initialize OpenGL context" << std::endl;
    return -1;
  }

};

Should I use a different loader? I am on OSX

Boost.log: How to prevent the output will be duplicated to all added streams when it uses the add_file_log() function?

I use the add_file_log() function to initialize a logging sink that stores log records into a text file. When I define several sinks, I have observed:

  • a file is created for each sink.
  • the output is copied to all files.

This is my logger:

class logger
{
public:
  logger(const logger&) =delete;
  logger(logger&&) =delete;
  logger& operator=(const logger&) =delete;
  logger& operator=(logger&&) =delete;

  static logger& get_instance(
    const std::string& file,
    bool console
  )
  {
      boost::log::register_simple_formatter_factory<
                                                    boost::log::trivial::severity_level,
                                                    char
                                                   >("Severity");

      std::string the_format = "[%TimeStamp%] (%LineID%) [%Severity%]: %Message%";

      if(!file.empty()) {
        boost::log::add_file_log(
          boost::log::keywords::file_name = file + "_%N.log",
          boost::log::keywords::rotation_size = 10 * 1024 * 1024,
          boost::log::keywords::time_based_rotation =
            boost::log::sinks::file::rotation_at_time_point(0, 0, 0),
          boost::log::keywords::auto_flush = true,
          //boost::log::keywords::open_mode = (std::ios::out | std::ios::app),
          boost::log::keywords::format = the_format
        );
      }

      boost::log::add_common_attributes();
      static logger instance{ the_format, console };
      return instance;
  }

  void log(
    const std::string& msg
  )
  {
      BOOST_LOG_SEV ( m_log_, boost::log::trivial::info ) << msg;
  }

private:
  boost::log::sources::severity_logger<
                                       boost::log::trivial::severity_level
                                      > m_log_;

  logger(
    const std::string& format,
    bool console
  )
  {
      if(console) {
        boost::log::add_console_log(
          std::clog,
          boost::log::keywords::format = format
        );
      }
  }
}; // logger

This is my main() function:

void test(
  const std::string& file
)
{
  logger& lg1 = logger::get_instance( file, false );
  lg1.log( "Hello" );
  lg1.log( "World" );
  lg1.log( "Bye" );
} // test

int main()
{
  unsigned char result = EXIT_SUCCESS;

  try
  {
    std::string file1 = "a.txt",
                file2 = "b.txt";
    logger& lg = logger::get_instance( file1, false );

    for(int i = 1; i<=10; i++) {
       lg.log( std::to_string(i) );
       if(i == 5) {
         test( file2 );
       }
    }
  }
  catch ( std::exception& e )
  {
    std::cerr << "Error: " << e.what() << std::endl;
    result = EXIT_FAILURE;
  }
  return result;
}

After running the example, the files contain:

a.txt_0.log

[2016-Aug-31 11:49:48.584353] (1) [info]: 1
[2016-Aug-31 11:49:48.585376] (2) [info]: 2
[2016-Aug-31 11:49:48.585418] (3) [info]: 3
[2016-Aug-31 11:49:48.585442] (4) [info]: 4
[2016-Aug-31 11:49:48.585462] (5) [info]: 5
[2016-Aug-31 11:49:48.585505] (6) [info]: Hello  <-- 
[2016-Aug-31 11:49:48.585610] (7) [info]: World  <-- Generated by second logger
[2016-Aug-31 11:49:48.585672] (8) [info]: Bye    <--
[2016-Aug-31 11:49:48.585709] (9) [info]: 6
[2016-Aug-31 11:49:48.585744] (10) [info]: 7
[2016-Aug-31 11:49:48.585777] (11) [info]: 8
[2016-Aug-31 11:49:48.585813] (12) [info]: 9
[2016-Aug-31 11:49:48.585842] (13) [info]: 10

b.txt_0.log

[2016-Aug-31 11:49:48.585505] (6) [info]: Hello
[2016-Aug-31 11:49:48.585610] (7) [info]: World
[2016-Aug-31 11:49:48.585672] (8) [info]: Bye
[2016-Aug-31 11:49:48.585709] (9) [info]: 6    <--
[2016-Aug-31 11:49:48.585744] (10) [info]: 7   <--
[2016-Aug-31 11:49:48.585777] (11) [info]: 8   <-- Generated by the first logger
[2016-Aug-31 11:49:48.585813] (12) [info]: 9   <--
[2016-Aug-31 11:49:48.585842] (13) [info]: 10  <--

How I can prevent this behavior? I want each file only stores the information generated by its associated logger.

Use Macro to add entities to doxygen group

In a very large code base I want to automatically add classes and functions to groups based on the project they are defined in. Luckily, I already have a compiler macro PROJECT_NAME_EXPORTED appended to each exported function and class:

enum PROJECT_NAME_EXPORTED MyEnum {}
class PROJECT_NAME_EXPORTED MyClass {}
PROJECT_NAME_EXPORTED void myFunction(int a)

The macro follows the same convention but is different for every subproject, e.g. SOME_PROJECT_EXPORTED, OTHER_EXPORTED. So having a list of all projects I do the following in my doxygen's CMake:

foreach(name ${LIST_OF_PROJECTS})
    SET(DOXYGEN_PREDEFINED_MACROS "${DOXYGEN_PREDEFINED_MACROS}\"${name}_EXPORTED=(void)/** @ingroup ${name}*/\" \\ \n")
endforeach()

And this almost works, the classes are listed correctly but the functions are listed with two return types (the actual one and the (void) I injected above):

void void myFunction(int a)

The culprit is obviously said injected (void) but if I leave it out, the classes are not correctly added to the group anymore.

Is there a different "dummy" word to add here or an entirely different solution for automatically adding all entities in a project to the corresponding doxygen group?

vector - swap two elements when elements have const members

I have the following code

class a {
public:
    const int aa;
    a(int aa) : aa(aa){}
};
int main() {
    std::vector<a> v;
    v.emplace_back(1);
    v.emplace_back(2);
    v.emplace_back(3);
    v.emplace_back(4);

    std::iter_swap(v.begin() + 1, v.rbegin());

    system("pause");
    return 0;
}

I get an error when I try to swap two elements of the vector.

Error   C2280   'a &a::operator =(const a &)': attempting to reference a deleted function

I understand it's because a has a constant member, but I am not able to figure out how to get this to work.

Why is my program crashing when compiling in Release mode? [Visual Studio 2015]

I'm working on a server, and i need to load data.Part of data i need to load is written in xml files so i writen a basic XMLDocumentParser.

const byte XMLDocumentParser::ParseXMLDocument(std::vector<XMLNode*>& out_nodes, const char * fileName)
    {
        std::ifstream file = std::ifstream(fileName, std::ifstream::ate);
        if (!file.is_open())
            return 1;
        unsigned int fileSize = file.tellg();
        file.seekg(std::ifstream::beg);

        char * buffer = new char[fileSize];
        file.read((char*)buffer, fileSize);
        file.close();
        if (fileSize <= 80)
        {
            return 2; // nothing to read
        }

        XMLNode * newNode = nullptr;
        int mainCursor = 0;
        for (size_t i = 0; i < 2; i++)
        {
            newNode = new XMLNode();
            mainCursor += GetNode(buffer, mainCursor, newNode);
            if (newNode)
            {
                out_nodes.push_back(newNode);
            }
        }


        delete[] buffer;
        buffer = 0;
        return 0;
    }

and the main recursive function

 int XMLDocumentParser::GetNode(char* buffer, int mainCursor, XMLNode* outNode)
{
    int argumentCursor = 0, valueCursor = 0, nameCursor = 0; byte result = 0;
    short argumentNameSize = 0, argumentValueSize = 0, nameSize;
    char* name = 0;


#pragma region NAME
    while (1)
    {
        if (buffer[mainCursor] == '<')
        {
            mainCursor++;

            while (buffer[mainCursor] == ' ')
                mainCursor++; //remove whiteSpaces

            nameCursor = mainCursor;

            while (buffer[nameCursor] != ' ' && buffer[nameCursor] != '>')
                nameCursor++;
            nameSize = nameCursor - mainCursor;
            if (nameSize <= 0)
            {
#ifdef XML_DEBUG
                result = 3;
                std::cout << "::NAME SIZE IS [" << nameSize << "] LINE[" << __LINE__ << "] ->ERROR\n\n";
#endif
                break;
            }

            name = new char[nameSize + 1];
            if (memcpy((void*)name, (const void*)&buffer[mainCursor], nameSize) == 0)
            {
#ifndef XML_DEBUG
                result = 4;
                std::cout << "::NAME MEMCPY FAILED NAMESIZE[" << nameSize << "] MAINCURRSOR[" << mainCursor << "] NAMECURSOR[" << nameCursor << "] ERROR\n\n";
#endif
                break;
        }
            mainCursor += nameSize;
            name[nameSize] = '\0';
            break;
    }
        mainCursor++;
}
#pragma endregion
    outNode->tagName = name;

    while (buffer[mainCursor] == ' ')
        mainCursor++; //remove whiteSpaces

    if (name[0] == '/')
        return mainCursor;

    //case <tagname> or <tagname/>
    if (buffer[mainCursor] == '/' && buffer[mainCursor + 1] == '>')
    {
        mainCursor += 2; //go past />
        return mainCursor;
    }
    else if (buffer[mainCursor] == '>')
    {
        XMLNode* childNode = nullptr;
        while (1)
        {
            childNode = new XMLNode();
            childNode->parentNode = outNode;
            mainCursor = GetNode(buffer, mainCursor, childNode);
            outNode->childNodes.push_back(childNode);
            char* toCheckName = new char[strlen(name) + 2];
            toCheckName[0] = '/';
            memcpy((void*)&toCheckName[1], (const void*)name, strlen(name) + 1);
            if (strcmp((const char*)toCheckName, (const char*)childNode->tagName) == 0)
            {
                delete[] toCheckName;
                toCheckName = 0;
                break;
            }
            delete[] toCheckName;
            toCheckName = 0;
        }
        return mainCursor;
    }

#pragma region ARGUMENTS
    while (1)
    {
        while (buffer[mainCursor] == ' ')
            mainCursor++; //remove whiteSpaces

        if (buffer[mainCursor] == '>') // node with no arguments
        {
            argumentCursor++; // go past >
            XMLNode* childNode = nullptr;
            while (1)
            {
                childNode = new XMLNode();
                childNode->parentNode = outNode;
                argumentCursor = GetNode(buffer, argumentCursor, childNode);
                outNode->childNodes.push_back(childNode);
                char* toCheckName = new char[strlen(name) + 2];
                toCheckName[0] = '/';
                memcpy((void*)&toCheckName[1], (const void*)name, strlen(name) + 1);
                if (strcmp((const char*)toCheckName, (const char*)childNode->tagName) == 0)
                {
                    delete[] toCheckName;
                    toCheckName = 0;
                    break;
                }
                delete[] toCheckName;
                toCheckName = 0;
            }

            mainCursor = argumentCursor;
            break;
        }
        else if (buffer[mainCursor] == '/' && buffer[mainCursor] == '>')
        {
            break;// no arguemtns , node finished
        }


        XMLNodeArgument * newArg = new XMLNodeArgument();
        valueCursor = 0; argumentCursor = mainCursor;


        while (1)
        {
            if (buffer[argumentCursor] == '\"' && valueCursor == 0)
            {
                if (buffer[argumentCursor + 1] == '\"') //case argName=""
                {
                    argumentCursor++;
                    valueCursor = argumentCursor;
                    argumentCursor++;
                    break;
                }

                argumentCursor++;
                valueCursor = argumentCursor;

            }
            else if (buffer[argumentCursor] == '\"' && valueCursor != 0)
            {
                argumentCursor++;
                break;
            }

            argumentCursor++;
        }

        argumentValueSize = argumentCursor - valueCursor - 1;
        argumentNameSize = valueCursor - mainCursor - 2;

        newArg->argumentName = new char[argumentNameSize + 1];
        newArg->argumentValue = new char[argumentValueSize + 1];

        if (memcpy((void*)newArg->argumentName, (const void*)&buffer[mainCursor], argumentNameSize) == 0)
        {
#ifdef XML_DEBUG
            result = 1;
            std::cout << "ARGUMENT NAME FAILED ARGUMENTCURSOR[" << argumentCursor << "] ARGUMENTNAMESIZE[" << argumentNameSize << "] MAINCURSOR[" << mainCursor << "] buffer[MAINCURSOR]=" << buffer[mainCursor] << "]\n";
#endif
            break;
        }
        if (memcpy((void*)newArg->argumentValue, (const void*)&buffer[valueCursor], argumentValueSize) == 0)
        {
#ifdef XML_DEBUG
            result = 1;
            std::cout << "ARGUMENT VALUE FAILED ARGUMENTCURSOR[" << argumentCursor << "] ARGUMENTNAMESIZE[" << argumentNameSize << "] MAINCURSOR[" << mainCursor << "] buffer[MAINCURSOR]=" << buffer[mainCursor] << "]\nARGUMENTVALUESIZE[" << argumentValueSize << "] ARGUMENTCUROSR[" << argumentCursor << "]\n";
#endif
            break;
        }

        newArg->argumentName[argumentNameSize] = '\0';
        newArg->argumentValue[argumentValueSize] = '\0';

        outNode->_arguments.push_back(newArg);

        while (buffer[argumentCursor] == ' ')
            argumentCursor++;

        if (buffer[argumentCursor] == '>')
        {
            argumentCursor++; // go past >
            XMLNode* childNode = nullptr;
            while (1)
            {
                childNode = new XMLNode();
                childNode->parentNode = outNode;
                argumentCursor = GetNode(buffer, argumentCursor, childNode);
                outNode->childNodes.push_back(childNode);
                char* toCheckName = new char[strlen(name) + 2];
                toCheckName[0] = '/';
                memcpy((void*)&toCheckName[1], (const void*)name, strlen(name) + 1);
                if (strcmp((const char*)toCheckName, (const char*)childNode->tagName) == 0)
                {
                    delete[] toCheckName;
                    toCheckName = 0;
                    break;
                }
                delete[] toCheckName;
                toCheckName = 0;
            }

            mainCursor = argumentCursor;
            break;
        }
        else if (buffer[argumentCursor] == '/' && buffer[argumentCursor + 1] == '>')
        {
            //we dont have ChildNodes return size
            argumentCursor += 2; //go past />
            mainCursor = argumentCursor;
            return mainCursor;
        }
        else if (buffer[argumentCursor] == '?' && buffer[argumentCursor + 1] == '>')
        {
            //we dont have ChildNodes return size
            argumentCursor += 2; //go past />
            mainCursor = argumentCursor;
            return mainCursor;
        }
        mainCursor += argumentNameSize + argumentValueSize + 3;
    }
#pragma endregion
    return mainCursor;
    }

Then i use this function to get desired data out of XMLNodes

    void XMLDocumentParser::BuildItems(XMLNode * mainnode, std::vector<IItem*>& out_items)
{
    for (size_t j = 0; j < mainnode->childNodes.size() - 1; j++)
    {
        XMLNode* node = mainnode->childNodes[j];
        XMLNodeArgument* arg = nullptr;
        IItem* out = new IItem();
        for (size_t i = 0; i < node->_arguments.size(); i++)
        {
            if ((arg = node->ConsumeArgument("id")))
            {
                out->_id = atoi((const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("name")))
            {
                out->_name = new char[strlen((const char*)arg->argumentValue)];
                strcpy((char*)out->_name, (const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("coolTime")))
            {
                out->_coolTime = atoi((const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("category")))
            {
                out->_category = itemCategoryDictionary[(const char*)arg->argumentValue];
            }
            else if ((arg = node->ConsumeArgument("level")))
            {
                out->_itemLevel = atoi((const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("rank")))
            {
                out->_rank = atoi((const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("maxStack")))
            {
                out->_maxStack = atoi((const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("rareGrade")))
            {
                out->_rareGrade = (ItemRareGrade)atoi((const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("requiredEquipmentType")))
            {
                out->_requiredEquipmentType = itemTypeDictionary[(const char*)arg->argumentValue];
            }
            else if ((arg = node->ConsumeArgument("combatItemType")))
            {
                out->_type = itemTypeDictionary[(const char*)arg->argumentValue];
            }
            else if ((arg = node->ConsumeArgument("requiredLevel")))
            {
                out->_requiredLevel = atoi((const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("artisanable")))
            {
                out->_artisanable = ((const char*)arg->argumentValue) == "True" ? 1 : 0;
            }
            else if ((arg = node->ConsumeArgument("dismantlable")))
            {
                out->_dismantlable = ((const char*)arg->argumentValue) == "True" ? 1 : 0;
            }
            else if ((arg = node->ConsumeArgument("enchantEnable")))
            {
                out->_enchantEnabled = ((const char*)arg->argumentValue) == "True" ? 1 : 0;
            }
            else if ((arg = node->ConsumeArgument("extractLook")))
            {
                //todo
            }
            else if ((arg = node->ConsumeArgument("guildWarehouseStorable")))
            {
                out->_guildBankStorable = ((const char*)arg->argumentValue) == "True" ? 1 : 0;
            }
            else if ((arg = node->ConsumeArgument("masterpieceRate")))
            {
                out->_masterpieceRate = atof((const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("obtainable")))
            {
                out->_obtainable = ((const char*)arg->argumentValue) == "True" ? 1 : 0;
            }
            else if ((arg = node->ConsumeArgument("sellPrice")))
            {
                out->_sellPrice = atoi((const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("slotLimit")))
            {
                out->_slotLimit = atoi((const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("sortingNumber")))
            {
                out->_sortingNumber = atoi((const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("storeSellable")))
            {
                out->_sellable = ((const char*)arg->argumentValue) == "True" ? 1 : 0;
            }
            else if ((arg = node->ConsumeArgument("tradable")))
            {
                out->_tradable = ((const char*)arg->argumentValue) == "True" ? 1 : 0;
            }
            else if ((arg = node->ConsumeArgument("unidentifiedItemGrade")))
            {
                out->_itemGrade = (ItemGrade)atoi((const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("useOnlyTerritory")))
            {
                out->_useOnlyTerritory = ((const char*)arg->argumentValue) == "True" ? 1 : 0;
            }
            else if ((arg = node->ConsumeArgument("warehouseStorable")))
            {
                out->_warehouseStoreable = ((const char*)arg->argumentValue) == "True" ? 1 : 0;
            }
            else if ((arg = node->ConsumeArgument("changeColorEnable")))
            {
                out->_changeColorEnable = ((const char*)arg->argumentValue) == "True" ? 1 : 0;
            }
            else if ((arg = node->ConsumeArgument("boundType")))
            {
                out->_bountType = itemBoundTypeDictionary[(const char*)arg->argumentValue];
            }
            else if ((arg = node->ConsumeArgument("requiredClass")))
            {
                out->_requiredClass = new char[strlen((const char*)arg->argumentValue)];
                strcpy((char*)out->_requiredClass, (const char*)arg->argumentValue);

            }
            else if ((arg = node->ConsumeArgument("linkMasterpiecePassivityCategoryId")))
            {
                out->_linkMasterpiecePassivityCategoryId = new char[strlen((const char*)arg->argumentValue)];
                strcpy((char*)out->_linkMasterpiecePassivityCategoryId, (const char*)arg->argumentValue);

            }
            else if ((arg = node->ConsumeArgument("linkPassivityCategoryId")))
            {
                out->_linkPassivityCategoryId = new char[strlen((const char*)arg->argumentValue)];
                strcpy((char*)out->_linkPassivityCategoryId, (const char*)arg->argumentValue);

            }
            else if ((arg = node->ConsumeArgument("linkPassivityId")))
            {
                out->_linkPassivityId = new char[strlen((const char*)arg->argumentValue)];
                strcpy((char*)out->_linkPassivityId, (const char*)arg->argumentValue);

            }
            else if ((arg = node->ConsumeArgument("linkCrestId")))
            {
                out->_linkCrestId = new char[strlen((const char*)arg->argumentValue)];
                strcpy((char*)out->_linkCrestId, (const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("linkCustomizingId")))
            {
                out->_linkCustomizingId = new char[strlen((const char*)arg->argumentValue)];
                strcpy((char*)out->_linkCustomizingId, (const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("linkEquipmentId")))
            {
                out->_linkEquipmentId = new char[strlen((const char*)arg->argumentValue)];
                strcpy((char*)out->_linkEquipmentId, (const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("linkLookInfoId")))
            {
                out->_linkLookInfoId = new char[strlen((const char*)arg->argumentValue)];
                strcpy((char*)out->_linkLookInfoId, (const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("linkPetAdultId")))
            {
                out->_linkPetAdultId = new char[strlen((const char*)arg->argumentValue)];
                strcpy((char*)out->_linkPetAdultId, (const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("linkPetOrbId")))
            {
                out->_linkPetOrbId = new char[strlen((const char*)arg->argumentValue)];
                strcpy((char*)out->_linkPetOrbId, (const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("linkSkillId")))
            {
                out->_linkSkillId = new char[strlen((const char*)arg->argumentValue)];
                strcpy((char*)out->_linkSkillId, (const char*)arg->argumentValue);
            }
            else if ((arg = node->ConsumeArgument("linkEnchantId")))
            {
                out->_linkEnchantId = new char[strlen((const char*)arg->argumentValue)];
                strcpy((char*)out->_linkEnchantId, (const char*)arg->argumentValue);

            }
            else if ((arg = node->ConsumeArgument("dropIdentify")))
            {
                out->_dropIdentify = ((const char*)arg->argumentValue) == "True" ? 1 : 0;
            }


        }
        out_items.push_back(out);
    }

}

The XMLDocumentParser::ParseXMLDocument goes well, but when i'm get IItems out of XMLNodes [as shown above] [with program compiled in Release mode VS2015] it crashes randomly at delete _arguments[i];

XMLDocumentParser::XMLNode::~XMLNode()
{
    if (tagName)
    {
        delete[] tagName;
        tagName = 0;
    }

    //clean arguments
    for (size_t i = 0; i < _arguments.size(); i++)
    {
        if (_arguments[i])
        {
            delete _arguments[i];
            _arguments[i] = 0;
        }
    }
    _arguments.clear();

    //clean childNodes
    for (size_t i = 0; i < childNodes.size(); i++)
    {
        if (childNodes[i])
        {
            delete childNodes[i];
            childNodes[i] = 0;
        }
    }
    childNodes.clear();

    parentNode = 0;
}

Why is that happening...Please help. Thanks!

I can't compeletly understand the coordinate system In the Cocos2d-x

for example, in this case: add menu to the layer, add control to the menu

result

why set the menu position zero and set menuItemLable position size/2 will get this result?

understand implementation of std::to_string

c++11 implements std::to_string, I took a look at the implementation. It calls vsnprintf internally. Okay, but why does it always set the size parameter as 4 times size of the type?

 inline string
 to_string(int __val)
 { return __gnu_cxx::__to_xstring<string>(&std::vsnprintf, 4 * sizeof(int),
                                          "%d", __val); }

 inline string
 to_string(unsigned __val)
 { return __gnu_cxx::__to_xstring<string>(&std::vsnprintf,
                                          4 * sizeof(unsigned),
                                          "%u", __val); }

 inline string
 to_string(long __val)
 { return __gnu_cxx::__to_xstring<string>(&std::vsnprintf, 4 * sizeof(long),
                                          "%ld", __val); }

C++11 condtional variable


I am trying make a lot of mistakes to learn Concurrency in C++11. I have to ask this,

Here is what this one is supposed to do: One queue, and three threads, one is suppose to put an integer into the queue, the other twos are suppose to correspondingly increase s1, s2 by popping the queue so that I can get total sum of numbers that were in the queue. To make it simpler I put 1 through 10 numbers into the queue.

But sometimes it works and sometimes it seems like there is an infinite loop:: what would be the reason?

#include <queue>
#include <memory>
#include <mutex>
#include <thread>
#include <iostream>
#include <condition_variable>
#include <string>

class threadsafe_queue {
private:
    mutable std::mutex mut;
    std::queue<int> data_queue;
    std::condition_variable data_cond;
    std::string log; //just to see what is going on behind
    bool done;

public:
    threadsafe_queue(){
        log = "initializing queue\n";
        done = false;
    }
    threadsafe_queue(threadsafe_queue const& other) {
        std::lock_guard<std::mutex> lk(other.mut);
        data_queue = other.data_queue;
    }
    void set_done(bool const s) {
        std::lock_guard<std::mutex> lk(mut);
        done = s;
    }
    bool get_done() {
        std::lock_guard<std::mutex> lk(mut);
        return done;
    }
    void push(int new_value) {
        std::lock_guard<std::mutex> lk(mut);
        log += "+pushing " + std::to_string(new_value) + "\n";
        data_queue.push(new_value);
        data_cond.notify_one();
    }
    void wait_and_pop(int& value) {
        std::unique_lock<std::mutex> lk(mut);
        data_cond.wait(lk, [this]{return !data_queue.empty();});
        value = data_queue.front();
        log += "-poping " + std::to_string(value) + "\n";
        data_queue.pop();
    }
    std::shared_ptr<int> wait_and_pop() {
        std::unique_lock<std::mutex> lk(mut);
        data_cond.wait(lk, [this]{return !data_queue.empty();});
        std::shared_ptr<int> res(std::make_shared<int>(data_queue.front()));
        log += "- popping " + std::to_string(*res) + "\n";
        data_queue.pop();
        return res;
    }
    bool try_pop(int& value) {
        std::lock_guard<std::mutex> lk(mut);
        if (data_queue.empty()) {
            log += "tried to pop but it was empty\n";
            return false;
        }
        value = data_queue.front();
        log += "-popping " + std::to_string(value) + "\n";
        data_queue.pop();
        return true;
    }
    std::shared_ptr<int> try_pop() {
        std::lock_guard<std::mutex> lk(mut);
        if (data_queue.empty()) {
            log += "tried to pop but it was empty\n";
            return std::shared_ptr<int>();
        }
        std::shared_ptr<int> res(std::make_shared<int>(data_queue.front()));
        log += "-popping " + std::to_string(*res) + "\n";
        data_queue.pop();
        return res;
    }
    bool empty() const {
        std::lock_guard<std::mutex> lk(mut);
        //log += "checking the queue if it is empty\n";
        return data_queue.empty();
    }

    std::string get_log() {
        return log;
    }

};

threadsafe_queue tq;
int s1, s2;

void prepare() {
    for (int i = 1; i <= 10; i++)
        tq.push(i);
    tq.set_done(true);
}

void p1() {
    while (true) {
        int data;
        tq.wait_and_pop(data);
        s1 += data;
        if (tq.get_done() && tq.empty()) break;
    }
}

void p2() {
    while (true) {
        int data;
        tq.wait_and_pop(data);
        s2 += data;
        if (tq.get_done() && tq.empty()) break;
    }
}

int main(int argc, char *argv[]) {
    std::thread pp(prepare);
    std::thread worker(p1);
    std::thread worker2(p2);
    pp.join();
    worker.join();
    worker2.join();

    std::cout << tq.get_log() << std::endl;
    std::cout << s1 << " " << s2 << std::endl;
    return 0;
}

mardi 30 août 2016

After calling destructor why member function will be called [duplicate]

This question already has an answer here:

I am not getting run time exception/error on below code. I called the member function Display() after destroying the object. Then why it still calls the function Display instead of compiler error? I am using Dev C++ ide.

Thanks in advance.

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

class Sample
{


int count ;

public:
    void Display()
    {
        cout << count << endl;
        cout << "Inside Sample::Display" << endl;
    }
};

int main()

{

Sample *ob = new Sample();

delete ob;

ob->Display();

return 0;   
}

Create alias for a list of types and passing it as a template parameter

I am using variadic templates to implement the visitor pattern, similarly to the implementation described in this answer. I have a lot of classes which must be visitable and several visitor classes, so I end up with a very long list of types when inheriting from the VisitableImpl and Visitor templates.

Since the same list of types would be used for both the Visitor and VisitableImpl, is there a more preferable, cleaner way to define an alias for it other than a preprocessor macro?

Cleaning up threads in a DLL: _endthreadex() vs terminatethread()

Because of the restrictions on DllMain (and I understood that the same applies to global&static object constructors&destructors in a DLL), such a simple thing as a singleton logger with asynchronous file writing/flushing thread becomes too tricky. The singleton logger is in a DLL, and I have limited influence on the executable loading and unloading this DLL time to time. I can force that executable to call my DLL initialization function before any use, so in the initialization function I can use a critical section to guard a variable telling whether the DLL has been already initialized or it needs init this time. This way initialization from DllMain is avoided, which would lead to a deadlock because I need to launch threads from initialization, and threads call DllMain with DLL_THREAD_ATTACH reason, and that obtains the same loader lock as the one already obtained when we are initializing in DllMain on DLL_PROCESS_ATTACH event.

C++11 thread cannot be used because of this bug (not fixed in MSVC++2013). So I'm using _beginthreadex(), because CreateThread documentation says:

A thread in an executable that calls the C run-time library (CRT) should use the _beginthreadex and _endthreadex functions for thread management rather than CreateThread and ExitThread; this requires the use of the multithreaded version of the CRT. If a thread created using CreateThread calls the CRT, the CRT may terminate the process in low-memory conditions.

But I have no control over the executable to ensure that some deinitialization function from the DLL is called before unloading the DLL. So the only options for cleanup are DllMain's DLL_PROCESS_DETACH and destructors of global/static variables. The problem is that they are called with loader lock obtained, so I cannot make there the DLL threads to exit gracefully because those threads upon a normal exit would attempt to call DllMain with DLL_THREAD_DETACH, which would result in a deadlock (loader lock again). MSDN suggests to use TerminateThread() to handle this:

DLL A gets a DLL_PROCESS_DETACH message in its DllMain and sets an event for thread T, signaling it to exit. Thread T finishes its current task, brings itself to a consistent state, signals DLL A, and waits infinitely. Note that the consistency-checking routines should follow the same restrictions as DllMain to avoid deadlocking. DLL A terminates T, knowing that it is in a consistent state.

So I'm afraid of using _beginthreadex() + TerminateThread() pair, instead of the designed _endthreadex() (the latter would be called by the thread itself if the thread returned normally).

tl;dr Consider a thread which returns from its entry function vs. a thread which does something like Sleep(INFINITE) in the end of its function waiting to get terminated (i.e. after it has got the resources consistent and signalled to the terminating thread that it's ready). Do some CRT or C++11 resources (like thread_local) etc. leak or get corrupted etc. if _endthreadex() is not called, but TerminatThread() is called instead?

Inconsistency in function type decay between variadic/non-variadic templates?

Given a non-variadic function template:

template<class T>
void f(void(t)(T));

And a plain function:

void f1(int);

This works:

f(f1);

The type of t becomes void (*)(int).

However, the variadic counterpart:

template<class... T>
void f(void(...t)(T));

does not work. The compilers (gcc & clang) complain about mismatched types void(T) and void (*)(int).

Note that if * is added explicitly, it works as it should:

template<class... T>
void f(void(*...t)(T));

So, why the non-variadic one can decay the function type while the variadic one cannot?

What is the name of this unusual C++ template feature used by Boost.Spirit?

The code below is from the Boost.Spirit x3 documentation. It uses an interesting C++ syntax that I've never seen before, which is nearly impossible to describe in a search query without knowing the proper terminology. Is this shorthand for the forward declaration of a class? Where is this feature mentioned in the C++ standard?

namespace parser
{
    using x3::eps;
    using x3::lit;
    using x3::_val;
    using x3::_attr;
    using ascii::char_;

    auto set_zero = [&](auto& ctx){ _val(ctx) = 0; };
    auto add1000 = [&](auto& ctx){ _val(ctx) += 1000; };
    auto add = [&](auto& ctx){ _val(ctx) += _attr(ctx); };

    // What is this? This is the very first use of the identifier `roman`.
    x3::rule<class roman, unsigned> const roman = "roman";
    //       ^^^^^^^^^^^

    auto const roman_def =
        eps                 [set_zero]
        >>
        (
            -(+lit('M')     [add1000])
            >>  -hundreds   [add]
            >>  -tens       [add]
            >>  -ones       [add]
        )
    ;

    BOOST_SPIRIT_DEFINE(roman);
}

std::upper_bound returns const iterator in const member function

Here is a class that contains a boost::circular_buffer of some struct. I make a typedef for iterators into the contained circular_buffer.

My problem is this: when the doWork function is marked const, the returned value of std::upper_bound is not compatible with the MyIterator type due to the return value having boost::cb_details::const_traits. If I remove the const keyword from the function, all my compile errors go away.

To be clear the compiler error is this:

error: conversion from ‘boost::cb_details::iterator::Sample, std::allocator::Sample> >, boost::cb_details::const_traits::Sample> > >’ to non-scalar type ‘Wrapper::MyIterator {aka boost::cb_details::iterator::Sample, std::allocator::Sample> >, boost::cb_details::nonconst_traits::Sample> > >}’ requested [](const Sample& a, const Sample& b) { return a.foo < b.foo; });

Here is a self-contained example:

#include <algorithm>
#include <boost/circular_buffer.hpp>

template <typename T>
class Wrapper {
 public:
    struct Sample {
        T foo;
    };

    typedef typename boost::circular_buffer<Sample>::iterator MyIterator;

    Wrapper(int size) { cb.resize(size); }

    void add(T val) { cb.push_back(Sample{val}); }

    void doWork(T bound) const {
        MyIterator iter =
            std::upper_bound(cb.begin(), cb.end(), Sample{3},
                         [](const Sample& a, const Sample& b) { return a.foo < b.foo; });
    }

    boost::circular_buffer<Sample> cb;
};

int main() {
    Wrapper<int> buf(100);
    buf.add(1);
    buf.add(5);
    buf.doWork(3);
    return 0;
}

So, why can't this function be const? Why does marking it const have this side-effect? I want a non-const iterator into the container, but in my real test case I don't intend to actually modify the container at all.

C++ binomial_distribution throws large number when type unsigned long?

When I type the binomial_distribution as an unsigned long it eventually throw a number that does not make sense although it seems legal to do so. Below is an example... What am I missing? Thanks in advance!

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <random>

using namespace std;

int main(int argc, const char * argv[])
{
    unsigned int    _RANDOM_SEED    = 1234;
    std::mt19937    _RANDOM_GENERATOR1(_RANDOM_SEED);

    unsigned long N = 3;
    double p = 0.02;
    unsigned long iter = 1000;

    // Distribution typed 'long'

    std::binomial_distribution<long> d(N, p);
    for(int i = 0; i < iter; i++) {
        unsigned long r = d(_RANDOM_GENERATOR1);
     cout << i << " " << r <<endl;
        if(r > N) {cout<<"PROBLEM"<<endl; exit(99);} // <-- never reached (which is good!)
    }

    // Distribution typed 'unsigned long'
    std::mt19937    _RANDOM_GENERATOR2(_RANDOM_SEED);

    std::binomial_distribution<unsigned long> d2(N, p);
    for(int i = 0; i < iter; i++) {
        unsigned long r = d2(_RANDOM_GENERATOR2);
        cout << i << " " << r <<endl;
        if(r > N) {cout<<"PROBLEM"<<endl; exit(99);} // <-- eventually reached, with r = huge number
    }
}

g++ --version Configured with: --prefix=/Applications/http://ift.tt/1d5DwEL --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn) Target: x86_64-apple-darwin13.4.0 Thread model: posix

Is there a way to forward argument to inner constexpr function?

The question: is it possible to evaluate constant expression inside a function by passing (maybe with some kind of "perfect forwarding") its argument to inner constexpr function? Example:

constexpr size_t foo(char const* string_literal) {
    return /*some valid recursive black magic*/;
}

void bar(char const* string_literal) {
    // works fine
    constexpr auto a = foo("Definitely string literal.");
    // compile error: "string_literal" is not a constant expression
    constexpr auto b = foo(string_literal);
}

template<typename T>
void baz(T&& string_literal) {
    // doesn't compile as well with the same error
    constexpr auto b = foo(std::forward<T>(string_literal));
}

int main() {
    // gonna do this, wont compile due to errors mentioned above
    bar("Definitely string literal too!");
}

Can't find anything clearly prohibiting in the documentation, but the solution isn't found, as well as a proof of impossibility. Constexpr'ness of inner expression is important.

interface function getting rvalue pointers to initialize shared_ptr

I have a class exposing through it's interface add function:

void AddObject(Object *o);

Inside the class I maintain the objects in set<shared_ptr<Object>>. Since I will create shared_ptr from the received pointer I thought to limit the function argument to only rvalue pointers so to make sure that the user will not delete the pointer I use. And so I'll change the function declaration to:

void AddObject(Object* &&o);

so a typical use will be:

AddObject(new Object())

preventing the user to accidentally delete pointer I hold. I don't want to to use shared_ptr in the interface because the user is not familiar with shared_ptr. Do you think my suggestion is a good idea?

write death test to verify std::set_terminate behavior

I'm using gtest to write some unit tests for exception handling code. As a simple example, let's say I want my program to abort on any unhandled exception, so I create the following test:

TEST_F(myFixture, myTest)
{
    std::set_terminate([](){std::abort(); });

    EXPECT_DEATH(throw std::runtime_error("terminate"), ".*");
}

I would expect this to succeed, since abort should be called on the program. However, my actual result is:

error: Death test: throw std::runtime_error("terminate")

Result: threw an exception.
Error msg:

[ DEATH ]
[ DEATH ] main.cpp(122):: Caught std::exception-derived exception escaping the death test statement. Exception message: terminate

[ DEATH ]

I think gtest's exception handlers are getting in the way. I've tried disabling them using the GTEST_CATCH_EXCEPTIONS environment variable, and the --gtest_catch_exceptions=0 command line flag as mentioned in the advanced guide, but I get the same result.

Am I doing something wrong, or is "death by exception" not something gtest can test for?

How can I implement a custom C++ iterator that efficiently iterates over key-value pairs that are backed by two distinct arrays

I want to make use of libstdc++'s __gnu_parallel::multiway_merge to merge four large sequences of sorted key-value pairs at once (to save memory bandwidth). Each sequence of key-value pairs is represented by two distinct arrays, such that values[i] is the value associated with keys[i].

The implementation for multiway-merging a single array of keys (keys-only) or an array of std::pairs would be straightforward. However, I need to implement a custom iterator that I can pass to the multiway_merge, which holds one reference to my keys array and one to the corresponding values array.

So my approach looks something like the following:

    template<
        typename KeyT,
        typename ValueT
    >
    class ForwardIterator : public std::iterator<std::forward_iterator_tag, KeyT>
    {
        KeyT* k_itr;
        ValueT* v_itr;
        size_t offset;

        explicit ForwardIterator(KeyT* k_start, ValueT *v_start) : k_itr(k_start), v_itr(v_start), offset(0)
        {
        }
        ForwardIterator& operator++ () // Pre-increment
        {
            offset++;
            return *this;
        }
    }

However, the problems start as soon as I'm getting to the overloading of the dereferencing operator.

Help is really appreciated! Thanks!

GLFW window reentrancy

I'm writing my own GLFW class wrapper and stumbled upon function reentrancy question.

GLFW documentation states that some functions are not reentrant (glfwCreateWindow, etc.) and "must not be called from any callback function".

Now consider the following code:

int main() {
    try {
        vkc::glfwWrapper a, b;

        a.createWindow(640, 520, "a");

        a.onClose = [&b](auto self) {
            b.createWindow(640, 520, "b");
        };
        b.onClose = [&a](auto self) {
            a.createWindow(640, 520, "a");
        };

        vkc::glfwWrapper::waitEvents();
    }
    catch (std::exception& e) {
        /* do stuff */
    }

    return 0;
}

onClose is a std::function thingy and is called on close callback. glfwCreateWindow will not be called with the GLFWwindow that belongs to callback. But what about GLFWwindow that does not belong to callback?

Wikipedia states that, "In computing, a computer program or subroutine is called reentrant if it can be interrupted in the middle of its execution, and then be safely called again ("re-entered") before its previous invocations complete execution." Technically that means it should be safe to do as I did, because I'm not interrupting anything, however that "any" really misleads me.

Why my merge_sort in c++ is not working?

This is my code for merge sort using vectors in c++. But it is throwing me weird result:

Result:

Input Elements: 11 33 12 44 99 34

Sorted Elements: 11 33 33 44 99 99

Code:

#include "stdafx.h"
#include "merger.h"
#include <iostream>
#include<array>
#include<vector>

//#define array_size(array) (sizeof((array))/sizeof((array[0])))

using namespace std;
template <typename T>
void merge_sort(vector<T>& arr, vector<T>& arr1, vector<T>& arr2) {
arr.clear();
int i = 0, j = 0, k = 0;

for (i = 0; i < arr1.size() && j < arr2.size(); k++) {
    if (arr1.at(i) <= arr2.at(j)) {
        arr.push_back(arr1.at(i));
        i++;
    }
    else if (arr1.at(i) > arr2.at(j)) {
        arr.push_back(arr1.at(j));
        j++;
    }
    k++;
}
while (i < arr1.size()) {
    arr.push_back(arr1.at(i));
    i++;
}

while (j < arr2.size()) {
    arr.push_back(arr2.at(j));
    j++;
    }

};

template <typename T>
vector<T>merge(std::vector<T>& arr) {
if (1 < arr.size()) {
    vector<T> arr1(arr.begin(), arr.begin() + arr.size() / 2);
    merge(arr1);//dividing to size 1

    std::vector<T> arr2(arr.begin() + arr.size() / 2, arr.end());
    merge(arr2);
    merge_sort(arr, arr1, arr2);

}
return (arr);
//write_vector(arr);
};


int main()
{
 //Merge Sort

vector<int> inputVec;
int size = 6;

for (int i = 0; i < size; i++) {
    int input;
    cin >> input;
    inputVec.push_back(input);
}

vector<int>& newSort=merge(inputVec);
vector<int>::iterator it;
for (it = newSort.begin(); it != newSort.end(); ++it)
    cout<<endl<< *it << endl;
return 0;
}

Result Window: My Output Can some one please point out what is wrong? Why it creates duplicate elements?

escape backslash in __FILE__ expansion

I'm string to create a std::regex(__FILE__) as part of a unit test which checks some exception output that prints the file name.

On Windows it fails with:

regex_error(error_escape): The expression contained an invalid escaped character, or a trailing escape.

because the __FILE__ macro expansion contains un-escaped backslashes.

Is there a more elegant way to escape the backslashes than to loop through the resulting string (i.e. with a std algorithm or some std::string function)?

Can a template template be specialized for fundamental types like regular templates?

I have written the following code to infix a templated class:

template<template<typename...> class C, typename A, typename B>
struct infix_t { typedef C<A,B> type; }
template<template<typename...> class C, class A>
constexpr infix_t<C,A> operator<(A, infix_t<C>) { return {}; }
template<template<typename...> class C, typename A, typename B>
constexpr C<A,B> operator>(infix_t<C,A>, B) { return {}; }

This allows me to write a <same_as> b where same_as has type infix_t<std::is_same>. However, if the type of A or B is a fundamental type, I get template template argument has different template parameters...; if I try to redeclare infix_t to accept fundamental types, I get template argument ... must be a class template or alias template. I thought that templates over typenames could accept fundamentals anyway. Is this because it's a template template, and the rules are different, or am I just approaching this wrong?

Template type-deduction performs implicit array-to-pointer conversion

I've read existing questions about this standard conversion. However, I didn't find a satisfying answer.

I have this piece of code which shows that the T* overload is chosen over the T&& one. From what I understood, the forwarding reference overload should bind everything, unless another overload is a perfect match.

In the following code, tab is a char const(&)[4].

Could someone explain to me why the array-to-pointer conversion is performed here? And if there is a way to workaround that conversion, I'm all ears!

(coliru link)

#include <utility>

template <typename T>
void f(T&& lol)
{
}

template <typename T>
void f(T* pof)
{
  static_assert(sizeof(T) && false, "");
}

template <typename T>
struct S;

int main(int argc, char *argv[])
{
  decltype("lol") tab = "lol";
  S<decltype(tab)> s;
  f("lol");
  return 0;
}

Parse integer from std::string, but fail if float

In C++ and C there are multiple methods to convert a string to integer, but I haven't found a conversion method that fails on parsing a floating point number.

const float fnum = std::stof("1.5");
std::cout << fnum << std::endl; // prints "1.5", all okay

const int inum = std::stoi("1.5");
std::cout << inum << std::endl; // prints "1", but wrong!

I need this to analyse a CSV file for column type. If all fields from one column are integers, then store the column as std::vector< int>, if float, then std::vector< float>, else store it as strings.

The only method that looks promising is this:

std::string num = "1.5";
char *end = nullptr;

const long lnum = strtol(num.data(), &end, 10);
if (end != &*num.end()) {
    std::cout << "Float? " << l << " / " << num << std::endl;
} else {
    std::cout << "Integer! " << l << " / " << num << std::endl;
}

This works, but is quite ugly. Is there a C++-way to solve this?

file read write with custom buffer

I'm currently fiddling out with raspberry pi gpio, the access files for which are located in /sys/class/gpio/ directory. Once correct pins are exported, we've to read and write onto the respective gpio files.

Now since those files will only contain either 0 or 1 at a moment, would providing a custom buffer via pubsetbuf call a good choice here? The call looks like -

file.rdbuf()->pubsetbuf(buf, sizeof buf);

I've read buffers are good for big read/writes since it provides less system calls and less number of read/writes if buffer size matches the required read/writes. But since here there is 0 possibility of big read/writes, only 0/1 would be written onto respective files, wouldn't having a large(default) buffer a bad choice here?

Should I set buffer and size as nullptr and 0 for direct read/write or some respective size of 0/1 chars so that buffering occurs but only for single characters, which is confusing since dosen't it means the same as the first choice? Or should I just leave the buffer size as it is and not even touch this function?

Also if I try to represent 0 and 1 as integers, what type size should my buffer be of? Currently I was doing it with string data type without pubsetbuf call, so never thought of that.

PS - I'm just trying to learn inner workings of c++ and linux so I'm not experimenting on some actual application where I might worsen things :p.

Is it possible to create an instance of a class within the same class?

Say I have a class:

class Foo{
public:

    Foo(){
    }

    //Is it possible to create a function like this:
    virtual Foo* createOb(){
       //Should create a new Foo,Bar or Fiz, depending on the actual object type.
    }
}

class Bar: public Foo{
public:

    Bar(){
    }
}

class Fiz: public Foo{
public:

    Fiz(){
    }
}

Is it possible to have a method createOb() in the base class, so when createOb() is called on an instance of one of the derived classes, that an instance of the derived class is created ?

Function with multiple return types

I have two enums which basically determine (on runtime) what to do. The 'mapping' looks something like

struct Foo { class CA; class CB; class CC; CA a; CB b; CC c; };
enum Base { A, B, C };
enum Func { X, Y };
Foo foo;

// A, X => use(foo.a.x());
// A, Y => use(foo.a.y());
// B, X => use(foo.b.x());
// B, Y => use(foo.b.y());

The problem is, that a, b and C, as well as the return types of x() and y() are all of different types (some really huge template types).

Mapping the two enums using switches or ifs is pretty ugly and requires lots of effort so I wondered, if I could somehow write something like this:

struct Foo { class CA; class CB; class CC; CA a; CB b; CC c; };
enum Base { A, B, C, };
enum Func { X, Y, }; 

template <typename T> auto applyFunc(Func f, T t)
{
    switch(f)
    {
        case Func::X: return t.x();
        case Func::Y: return t.y();
    }
}


auto getBase(Base b, Foo f)
{
    switch(bt)
    {
        case BaseType::A: return f.a;
        case BaseType::B: return f.b;
        case BaseType::C: return f.c;
    }
}


Func f;
Base b;
Foo foo;

use(applyFunc(f, getBase(b, foo)));

Final enum classes in C++11

I am just curious whether an enum class can be final or not ... since the compilers are giving me contradictory results.

Consider the code:

#include <iostream>

enum class some_enums final : char
{
    a = 'a', 
    b = 'b',
    c = 'c'
};

int main()
{
    some_enums aa = some_enums::a;
    std::cout << "aa=" << static_cast<char>(aa) << std::endl;
}

Compiling this with Visual Studio 2015 compiler (http://ift.tt/28Tayem) works... however compiling it with clang (http://ift.tt/2bynScT) gives me an error:

source_file.cpp:3:30: error: expected ';' after top level declarator
        enum class some_enums final : char

I have seen no traces of final enum classes anywhere in the standard so I give credit to clang ... however why does Visual Studio accept it in this case although it is not mentioned in MSDN (http://ift.tt/2byCMLn) ?

lundi 29 août 2016

Parsing a pointer into a void

Hey sorry if this is a dumb question, my prof. quickly went over pointers and then moved on and I am currently confused.

My prof wants us to use her code here:

void getStopWords(char *ignoreWordFileName, vector<string& _vecIgnoreWords){
return;}

(I know this will return nothing currently, I need to add code to this such as opening the ignoreWordFileName file and adding every line to the vector) and I am confused how I would call this void in the main function. I have to use a command line argument to get the filename so in my case:

fileNameIgnore = argv[3];

How would I then call the void using my fileNameIgnore? Again sorry for the dumb question, I have researched some and have been unable to find information on this. Thank you.

Text file has 1 or 2 or 3 strings followed by doubles. How do I read strings?(each line has 1 or 2 or 3 string in the beginning)

I'm still new to c++(and to stackoverflow). I'm creating program to analyze some data for me(open file, save data into vectors, then I search vectors for name, and then I work with objects functions). Anyways, previous "version" of the program works fine, but file that I open only contains 1 string per line in the beginning(followed by other data), so it's easy to work with. What I'm trying to do, is to open up the files that contain 1-3 strings(i.e. line 1 - West Ham United, line 2 - Everton etc.). After the name, other data follows on the same line. I thought about separating the name and other data into 2 lines, in example Line1 - name, Line2 - other data, and so on. But how do I save the whole "name" line into vector(vector is of the object type). Other option would be to open up the file and saving all of the chars into an array. Afterwards I would output that array in Outfile, deleting the spaces only between letters(i.e. - WestHamUnited), and then I would work with the output file. Question is, how do I delete the spaces only between letters? Maybe you guys could recommend some other option that I'm not aware of.

c++ both if and else are not executed-

I have a similar production code

void func(const char *a, int size){ 
...
if(a && size > 0)
{..}
else
{..}
}

though the func works perfectly in most of the cases, in one case it is neither hitting if nor else. I used gdb to verify the the value of a and size. The condition turns out true when I evaluate it with a bool. I have no clue what is happening.

could it be anything to do with memory corruption? I ran valgrind. There is no corruption though there are a lot of memory leaks.

Using A Class within my program C++

I am a fairly new programmer. I am trying to implement a function to add an Element to my list, (which is use bit-strings to represent a set for small positive integers [0, 64))

Here is my Class class SmallSet { public: SmallSet(): set(0) {} bool addElement(unsigned long); // add a new element to the set. No-op if input is invalid. bool deleteElement(unsigned long); // delete an element from the set. No-op if not a member. bool isMember(unsigned long); // test membership unsigned numElements(); // returns the cardinality of the set void printElements(); // prints members from smallest to largest.

private: unsigned long set; // internal representation of our set.

SmallSet &operator=( const SmallSet &);   // disallow assignment
SmallSet( const SmallSet &);              // disallow copy-constructor

};

// My function i am using is called

bool addElement(unsigned long x) // add a new element to the set. No-op if input is invalid. {

} I am trying o pass an element into the set/ add an element what is the proper way to do this, Thanks in advance!

Exception is not handled on fstream open

Context

I have this simple code:

#include <iostream>
#include <fstream>
#include <system_error>

int main(int argc, char *argv[]) {
  std::ifstream file;
  file.exceptions(std::ios::failbit | std::ios::badbit);

  try {
    file.open("a_file_does_not_exist.txt", std::ios::in);
    file.close();
  } catch(const std::ios_base::failure& err) {
    std::cerr << err.code() << std::endl;
    return -1;
  }

  return 0;
}

Just to complete, this is compile command:

 g++ -std=c++11 -g //  ...

The version of compiler is g++ (GCC) 6.1.1.

Platform: arch-linux 4.7.2-1.


The problem

As you can imagine, the file does not exists so the method file.open(...) will throw an exception. The problem is when I run the code an exception is not handled, and std::terminate is called.

The strange thing is the output:

terminate called after throwing an instance of 'std::ios_base::failure'
  what():  basic_ios::clear
Annullato (core dump creato)

As you can read, the throwing class is a std::ios_base::failure, but my catch is right that class.

My question is: what am I missing?

C++11 lambda operator namespace conflict

I have three files, main.cpp, a.cpp and b.cpp. The main() function just calls a function in a.cpp, and then in b.cpp -- and I get a SIGSEGV. As far as I can tell, it looks like the lambda functions used with my sort() are conflicting with each other. Compile command line order is important; if I compile the files via:

g++ -std=c++11 main.cpp a.cpp b.cpp

The code crashes (I get "*** stack smashing detected ***: ./a.out terminated"), but if I switch "a.cpp" and "b.cpp":

g++ -std=c++11 main.cpp b.cpp a.cpp

it runs fine (I'm not saying anything about whether it "works" or not, just SIGSEGV vs no-SIGSEGV).

Here's the smallest code samples I could generate for the three files:

main.cpp:

extern void spud1 (void);
extern void spud2 (void);

int
main (int argc, char **argv)
{
    spud1 ();
    spud2 ();
}

a.cpp:

#include <vector>
#include <string>
#include <algorithm>

using namespace std;

struct Database
{
    int     pubdate;
    string  title;
    string  link;
};

static vector <Database> database;

void
spud1 (void)
{
    int     i;

    for (i = 0; i < 20; i++) {
        database.push_back ({});
    }

    sort(database.begin(), database.end(),
        [] (const Database& a, const Database& b)
        {
            return (a.pubdate > b.pubdate);
        });
}

b.cpp:

#include <vector>
#include <string>
#include <algorithm>

using namespace std;

struct Database
{
    unsigned        serial;
    double          calories;
    double          carbs;
    double          sodium;
    double          sugar;
};

static vector <Database> database;

void
spud2 (void)
{
    int     i;

    for (i = 0; i < 20; i++) {
        database.push_back ({});
    }

    sort(database.begin(), database.end(),
        [] (const Database& a, const Database& b)
        {
            return (a.serial > b.serial);
        });
}

There are two things that bother me about this:

  1. there's no indication from the toolchain that "something bad" is happening; there are no compiler or linker warnings, and
  2. I have no way to make "struct Database" local to the module -- if I stick "static" in front of it I get an error: "a.cpp:13:1: error: a storage class can only be specified for objects and functions**`"

So, my question is, what am I doing wrong, and how can I get around it? (i.e., why is there no warning, is this "supposed" to happen? and how do I make my "Database" struct actually be local to the module? -- my workaround is to use different names, but I'm not happy with that.)

Inheritance and member functions

Consider I have series of derived classes for example as listed below:

class A
{
...
}

class B1 : public A //there may be many B's here say, B2, B3 etc
{
 ...
}
class C1 : public B1 //may be more C's as well
{
...
}

I would like to put all of the objects in single container, thus all would be of type class A.

Suppose I would like to add a function to class C1, what would be the best way to achieve this? My options would be introducing it in the base class A and write the needed implementation in C1, or, I could introduce it in C1 and do dynamic casting to access it. Which one is preferred? Is dynamic casting too expensive? (My main constrain is the run time.I have a flag in the base class to indicate what type of derived object it is, thus I do not have to dynamic cast every object in the container. Does adding unnecessary functions to base class can result in bad instruction cache use?)

Circular buffer with smart_ptr and weak_ptr?

I can't find a complete example that shows how to eliminating strong circular references between shared_ptr.

Problem is how to use a weak_ptr to "close" the chain of generic elements and to access the "next" element with the weak_ptr.

Thank you.

control of base constructor in derived classes, potential double-initialization

Regarding this question and the answer to it there does seem to be an exception, but it raised more questions for me than answering them. Consider this:

#include <iostream>
using namespace std;
struct base {
  virtual void test() {cout << "base::test" << endl;}
  base() {test();}
  virtual ~base() {}
};
struct derived : base {
  virtual void test() {cout << "derived::test" << endl;}
  derived() : base() {}
  ~derived() {}
};
int main() {
  derived d;
  return 0;
}

I naively thought this would only print either of the two messages. It actually prints both - first the base version then derived. This behaves the same on -O0 and -O3 settings, so it's not an optimization or lack thereof as far as I can tell.

Am I to understand that calling base (or higher / earlier classes' constructors) within a derived constructor, will not prevent the default base constructor (or otherwise) from being called beforehand?

That is to say, the sequence in the above snippet when constructing a derived object is: base() then derived() and within that base() again?

I know it doesn't make sense to modify the vtable just for the purposes of calling base::base(), back to what it was before derived::derived() was called, just for the sake of calling a different constructor. I can only guess that vtable-related things are hard-coded into the constructor-chain and calling previous constructors is literally interpreted as a proper method call (up to the most-derived object having been constructed in the chain so far)?

These minor questions aside, it raises two important ones:

1. Is calling a base constructor within a derived constructor always going to incur calling the default base constructor prior to the derived constructor being called in the first place? Is this not inefficient?

2. Is there a use-case where the default base constructor, per #1, shouldn't be used in lieu of the base constructor explicitly called in a derived classes' constructor? How can this be achieved in C++?

I know #2 sounds silly, after all you'd have no guarantee the state of the base class part of a derived class was 'ready' / 'constructed' if you could defer calling the base constructor until an arbitrary function call in the derived constructor. So for instance this:

derived::derived() { base::base(); }

... I would expect to behave the same way and call the base constructor twice. However is there a reason that the compiler seems to treat it as the same case as this?

derived::derived() : base() { }

I'm not sure. But these seem to be equivalent statements as far as observed effects go. It runs counter to the idea I had in mind that the base constructor could be forwarded (in a sense at least) or perhaps a better choice of word would be selected within a derived class using :base() syntax. Indeed, that notation requires base classes to be put before members distinct to the derived class...

In other words this answer and it's example (forget for a moment its C#) would call the base constructor twice? Although I understand why it would be doing that, I don't understand why it doesn't behave more "intuitively" and select the base constructor (at least for simple cases) and call it only once.

Isn't that a risk of double-initializing the object? Or is that part-and-parcel of assuming the object is uninitialized when writing constructor code? worst case do I now have to assume that every class member could potentially be initialized twice and guard against that?

I'll end with a horrible example - but would this not leak memory? should it be expected to leak?

#include <iostream>
using namespace std;
struct base2 {
  int * member;
  base2() : member(new int) {}
  base2(int*m) : member(m) {}
  ~base2() {if (member) delete member;}
};
struct derived2 : base2 {
  derived2() : base2(new int) {
    // is `member` leaking?
    // should it be with this syntax?
  }
};
int main() {
  derived2 d;
  return 0;
}

std::cin with more complex objects

I have a text file which first describes some lines and then describes some colorful lines:

1 2    3  4
5 6    7  8 
9 10   11 12

red    1 0 0    1 2    3 4
green  0 1 0    5 6    7 8
blue   0 0 1    9 10   11 12

The number of lines in each section is unknown at time of execution
I overloaded the std::cin >> operator for these structs:

struct Point { int x, y; }
struct Line { Point a, b; }
struct Color { float r, g, b; std::string name; };
struct ColorfulLine { Line line; Color color; };

(Full example here: http://ift.tt/2c40kJF)
Now I need to iterate over the file using Lines and ColorfulLines:

Line line;                                                     
while(cin >> line) { cout << "We've got a line!\n"; }              

ColorfulLine color_line;                                         
while(cin >> color_line) { cout << "We've got a colorful line!\n"; } 

// actually I'm putting them into std::lists but I skipped this part for simplicity

And here is the problem - the colorful lines are never fetched, i.e. the second loop is not executed.

I have an assumption why it happens but don't know how to fix it:
When std::cin tries to fetch the 4th Line, it fails because instead of a number there's the string "red".
Next, in the second while loop, std::cin tries to read a string (Color.name) but it sees a number, and then fails too.

I tried to put some random word before the ColorfulLines section hoping that when the first loop fails, the second will start reading from the "red" string, but it didn't.

How to fix this?