jeudi 28 décembre 2017

What does "using X = int(&)()" do?

I have been seen following type of code when i browsing Quora.

#include <iostream>
int f() { return 1; }
int main()
{
    int (&var1)() = f;
    using X = int(&)();
    int i = reinterpret_cast<X>(var1)();
    std::cout << " i = " << i << '\n';
}

So, What does using X = int(&)() do?

How to use std::pointer_safety

I just found this: http://ift.tt/2DqG4OQ

But I don't know how to use it.

Is there some simple example?

Accessing an atomic member of a class held by a shared_ptr

I'm trying to create a small class that will allow me to facilitate a communication between two threads.

Those threads most probably will outlive the context in which the above mentioned class was created as they are queued onto a thread pool.

What I have tried so far (on coliru as well):

class A    
{
public:
    A(int maxVal) : maxValue(maxVal) {}    
    bool IsOverMax() const { return cur >= maxValue; }    
    void Increase() { cur++; }

private:
    const int  maxValue;    
    atomic_int cur{ 0 };
};

possible usage:

void checking(const shared_ptr<A> counter)
{
    while(!counter->IsOverMax())
    {
        cout<<"Working\n";         // do work
        std::this_thread::sleep_for(10ms);
    }
}

void counting(shared_ptr<A> counter)
{
    while (!counter->IsOverMax())
    {
        cout<<"Counting\n";
        counter->Increase(); // does this fall under `...uses a non-const member function of shared_ptr then a data race will occur`?  http://ift.tt/1jrtS5s
        std::this_thread::sleep_for(9ms);
    }
}

int main() 
{ 

    unique_ptr<thread> t1Ptr;
    unique_ptr<thread> t2Ptr;

    {
        auto aPtr = make_shared<A>(100); // This might be out of scope before t1 and t2 end
        t1Ptr.reset(new thread(checking, aPtr)); // To simbolize that t1,t2 will outlive the scope in which aPtr was originaly created
        t2Ptr.reset(new thread(counting, aPtr));
    }

    t2Ptr->join();
    t1Ptr->join();
    //cout<< aPtr->IsOverMax();
}

The reason I'm concerned is that the documentation says that:

If multiple threads of execution access the same std::shared_ptr object without synchronization and any of those accesses uses a non-const member function of shared_ptr then a data race will occur unless all such access is performed through these functions, which are overloads of the corresponding atomic access functions (std::atomic_load, std::atomic_store, etc.)

  • So Increase is a non const function, are the copies of aPtr are the same std::shared_ptr for this context or not ?
  • Is this code thread-safe?
  • In any case why?

Iterating through vector of vectors in C++

I am trying through vector of vectors (2D vector) in C++. I used method from this answer. Here is code.

#include <iostream>
#include<vector>

void printVec(std::vector<std::vector<double>> *v1)
{
    //displaying vector v1
    std::vector <std::vector<double> >::const_iterator row;
    std::vector<double>::const_iterator col;

    std::cout<<"Displaying vectors";

    for (row = v1->begin(), row != v1->end(); ++row) //error 
    {
        for (col = row->begin(); col != row->end(); ++col)
        {
            std::cout << *col << " ";
        }
        std::cout <<std::endl;
    }
}
int main()
{
    int nRowA, nColA;
    nRowA = 2;
    nColA = 4;

    std::vector< std::vector<double>> A, B, C;
    std::vector<double> temp1;

    //creating multidimensional vector A
    for (int i = 0; i < nRowA; ++i) 
    {
        for (int j = 0; j < nColA; ++j)
        {
            temp1.push_back(j+1);
        }
        A.push_back(temp1);
    }

    //Displaying vector A
    printVec(&A);
    return 0;
}

I am creating a vector in main() is passing it by pointer to printVec(). In printVec(), I am using iterators to iterate through this 2D pointer. But getting error at the row indicated in the code as //error. Can someone tell what is going wrong?

(I am aware about using range for loop and passing vector of vector as reference instead of as pointer. )

Copy constructor called on object instantiation

I may just be miss reading this code but in my attempt to call the default constructor, the code instead calls the copy constructor on my proposed creation.

Could someone give me a knowledge bomb on where my mental model and this code done meet :-/

Below is the code written, its a rough outline for a unique_handler that will hold data by a pointer defined by a trait. This is not relevant but the confusion is in why the auto h = new unique_handler(new My_handler()); performs a copy constructor call instead of a default constructor call.

#include "../psInclude/my_util.h"

namespace mlekena_smart_class{
    template<typename Traits>
    class unique_handle{

        typedef typename Traits::pointer pointer;

        pointer m_value;
        //...

        public:

        // Delete the copy constructor
        unique_handle(const unique_handle &u_handle) = delete;

        explicit unique_handle(pointer value = Traits::invalid()) throw():
        m_value(value)
        {
        }

        auto get() const throw() -> pointer
        {
            // ...
        }

        auto release() throw() -> pointer
        {
            // ...
        }

        auto reset(pointer value = Traits::invalid) -> bool
        {
            // ...
        }

        ~unique_handle() throw()
        {
            // ..
        }

        explicit operator bool() const throw()
        {
            // ..
        }
    };
    struct null_handle_traits{

        typedef HANDLE pointer;

        // ...
    }

    using namespace mlekena_smart_class;
    using namespace std;

    struct My_handle{
    int id;
    const char* handle;

    My_handle(int _id, const char* h): id(_id), handle(h){}
        ~My_handle(){}
    };

    int main(){

        // offending code
        auto h = null_handle{new My_handle(1, "Handler")};

        // ...

    }
}

boost::python how to pass data to construct an object in python

I am using boost::python to call some python code from C++.

std::string input = "{\"x\":1}";
auto objectpath = boost::python::import("objectpath");
auto Tree = objectpath.attr("Tree")(input);
auto tree = Tree.attr("execute")("$..x");

In python the corresponding execution is (objectpath):

$ python
>>> from objectpath import *
>>> tree=Tree({"a":1})
>>> tree.execute("$.a")
1

But in C++ I am getting an error:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/objectpath/core/interpreter.py", line 608, in execute
    ret=exe(tree)
  File "/usr/local/lib/python2.7/dist-packages/objectpath/core/interpreter.py", line 258, in exe
    fst=exe(fst)
  File "/usr/local/lib/python2.7/dist-packages/objectpath/core/interpreter.py", line 246, in exe
    return self.data
AttributeError: 'Tree' object has no attribute 'data'
Python error, but failed to get the reason via PyErr

How can I fix my C++ problem?

std::ofstream crash on construction when called from GC thread

I attempt to do debug logging to a file in one of the destructors. In our application, this happens to be on the GC [Finalizer] thread (since I want to do logging in our native library that is running in a managed context - a .NET application).

The problem is, that I can't construct std::ofstream - it crashes during construction. Seems like std::locale::facet object is already destroyed.

I attach a screenshot with a relevant call stack, code and an exception:

enter image description here

The bit of code that tries to create an ofstream object is just that:

SpatialRenderer::~SpatialRenderer()
{
    // dump
    std::ofstream f("dump.txt"); // <- crash at this line
    // writing to f here
}

Environment: Windows 10, Visual Studio 2017 Version 15.4.5