小编bru*_*ery的帖子

为什么GoogleMock泄露了我的shared_ptr?

我使用GoogleMock/GoogleTest进行测试,当匹配器将模拟器的shared_ptr作为参数时,我会看到一些奇怪的行为,并且在同一个shared_ptr上调用EXPECT.令人讨厌的代码:

#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
using namespace boost;
using namespace testing;

struct MyParameter
{
    virtual ~MyParameter() {}
    virtual void myMethod() = 0;
};

struct MyParameterMock : public MyParameter
{
    MOCK_METHOD0(myMethod, void());
};

struct MyClass
{
    virtual ~MyClass() {}
    virtual void myMethod(shared_ptr<MyParameter> p) {}
};

struct MyClassMock : public MyClass
{
    MOCK_METHOD1(myMethod, void(shared_ptr<MyParameter>));
};

TEST(LeakTest, GoogleMockLeaksMatchedPointer)
{
    shared_ptr<MyClassMock> c = make_shared<MyClassMock>();
    shared_ptr<MyParameterMock> p = make_shared<MyParameterMock>();
    {
        InSequence dummy;
        EXPECT_CALL(*c, myMethod(Eq(p)));
        EXPECT_CALL(*p, myMethod());
    }
    c->myMethod(p);
    p->myMethod();
}
Run Code Online (Sandbox Code Playgroud)

当这个测试运行时,我明白了 …

c++ boost googletest shared-ptr googlemock

28
推荐指数
1
解决办法
2万
查看次数

在Boost :: range中编写适配器

我开始玩Boost :: Range,以便在C++中使用延迟转换管道.我现在的问题是如何在较小的部分拆分管道.假设我有:

int main(){
  auto map = boost::adaptors::transformed; // shorten the name
  auto sink = generate(1) | map([](int x){ return 2*x; })
                          | map([](int x){ return x+1; })
                          | map([](int x){ return 3*x; });
  for(auto i : sink)
    std::cout << i << "\n";
}
Run Code Online (Sandbox Code Playgroud)

我想用a替换前两个地图magic_transform,即:

int main(){
  auto map = boost::adaptors::transformed; // shorten the name
  auto sink = generate(1) | magic_transform()
                          | map([](int x){ return 3*x; });
  for(auto i : sink)
    std::cout << i << …
Run Code Online (Sandbox Code Playgroud)

c++ boost functional-programming boost-range

11
推荐指数
1
解决办法
2346
查看次数

boost :: adapters :: transformed后跟boost :: adapters :: filtered调用函数两次

我试图将一个boost::adaptors::transformed(让我们称之为map)链接到boost::adaptors::filtered(让我们称之为filter) - 这个想法是在一个范围内映射一个fun返回"Maybe"(在我的情况下,a std::pair<bool, T>)并仅输出部分结果.我的第一个实施:

define BOOST_RESULT_OF_USE_DECLTYPE // enable lambda arguments for Boost.Range
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/adaptor/transformed.hpp>

struct OnlyEven
{
    typedef int argument_type;
    typedef std::pair<bool, int> result_type;
    result_type operator()(argument_type x) const
    {
        std::cout << "fun: " << x << std::endl;
        return std::make_pair(x % 2 == 0, x);
    }
} only_even;

int main(int argc, char* argv[])
{
    auto map = boost::adaptors::transformed;
    auto filter = boost::adaptors::filtered;
    int v[] = {1, 2, …
Run Code Online (Sandbox Code Playgroud)

c++ boost functional-programming boost-range

11
推荐指数
1
解决办法
2195
查看次数

在C++中进行延迟转换

我有以下Python代码片段,我想用C++重现:

from itertools import count, imap

source = count(1)
pipe1 = imap(lambda x: 2 * x, source)
pipe2 = imap(lambda x: x + 1, pipe1)
sink = imap(lambda x: 3 * x, pipe2)
for i in sink:
    print i
Run Code Online (Sandbox Code Playgroud)

我听说过Boost Phoenix,但我找不到transform像Python那样懒惰行为的例子imap.

编辑:为了澄清我的问题,我们的想法不仅仅是使用a来按顺序应用函数for,而是能够使用像std::transform无限生成器这样的算法.函数的组合方式(使用方言等功能更强的语言)也很重要,下一步是函数组合.

更新:感谢bradgonesurfing,David Brown和Xeo的惊人答案!我之所以选择Xeo是因为它是最简洁的,它让我在我想要的地方得到了正确的结果,但是David对于理解这些概念非常重要.此外,bradgonesurfing的倾斜Boost :: Range :).

c++ python functional-programming lazy-evaluation

10
推荐指数
2
解决办法
1565
查看次数

时间戳传出数据包

我正在尝试获取传出数据包的准确时间戳(使用原始套接字发送).根据Linux/Documentation/networking/timestamping.txt,"对于发送时间戳,传出的数据包将循环回到套接字的错误队列,并附带发送时间戳.可以使用recvmsg(flags = MSG_ERRQUEUE)接收."

不幸的是,recvmsg总是返回-1时,在原始套接字调用(与创建socket(PF_INET, SOCK_RAW, IPPROTO_RAW),并与SO_TIMESTAMP设置为1使用setsockopt).我究竟做错了什么?有没有更好的方法来获得传出数据包的准确时间戳?

附录(资料):

我还尝试从通过UDP套接字发送的数据包中获取时间戳(下面的源代码)并recvmsg返回-1:错误是"资源暂时不可用"(EAGAIN).

附录(源代码):

#include <arpa/inet.h>
#include <linux/net_tstamp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>

void die(char* s)
{
    perror(s);
    exit(1);
}

int main(int argc, char* argv[])
{
    char* destination_ip = "10.0.0.1";
    int destination_port = 1234;

    int sock;
    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
        die("socket()");
    }

    int timestamp_flags = …
Run Code Online (Sandbox Code Playgroud)

c linux timestamp raw-sockets

9
推荐指数
2
解决办法
1万
查看次数

itertools.tee等效于Boost :: Range?

Python itertools具有teen-plicating iterables:

def tee(iterable, n=2):
    it = iter(iterable)
    deques = [collections.deque() for i in range(n)]
    def gen(mydeque):
        while True:
            if not mydeque:             # when the local deque is empty
                newval = next(it)       # fetch a new value and
                for d in deques:        # load it to all the deques
                    d.append(newval)
            yield mydeque.popleft()
    return tuple(gen(d) for d in deques)
Run Code Online (Sandbox Code Playgroud)

我找不到相应的东西Boost::Range.我错过了什么或者我应该自己滚动吗?

c++ boost boost-range

9
推荐指数
1
解决办法
637
查看次数

boost :: asio异步条件

我们的想法是能够在消费者/生产者问题上用boost :: asio和线程池替换多线程代码.目前,每个消费者线程等待boost::condition_variable- 当生产者向队列添加内容时,它调用notify_one/ notify_all通知所有消费者.现在当你(可能)拥有1k +消费者时会发生什么?线程不会扩展!

我决定使用boost::asio,但后来我遇到了它没有条件变量的事实.然后async_condition_variable诞生了:

class async_condition_variable
{
private:
    boost::asio::io_service& service_;
    typedef boost::function<void ()> async_handler;
    std::queue<async_handler> waiters_;

public:
    async_condition_variable(boost::asio::io_service& service) : service_(service)
    {
    }

    void async_wait(async_handler handler)
    {
        waiters_.push(handler);
    }

    void notify_one()
    {
        service_.post(waiters_.front());
        waiters_.pop();
    }

    void notify_all()
    {
        while (!waiters_.empty()) {
            notify_one();
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

基本上,每个消费者都会打电话async_condition_variable::wait(...).然后,制作人最终会打电话async_condition_variable::notify_one()async_condition_variable::notify_all().将调用每个消费者的句柄,并且可以根据条件行事或async_condition_variable::wait(...)再次致电.这是可行的还是我在这里疯了?应该执行什么样的锁定(互斥),因为这将在线程池上运行?

PS:是的,这更像是一个RFC(征求意见)而不是一个问题:).

c++ multithreading boost boost-asio

6
推荐指数
1
解决办法
2243
查看次数

异步libpcap:丢失数据包?

我有一个程序,它将一组TCP SYN数据包发送到主机(使用原始套接字)并使用libpcap(使用过滤器)来获取响应.我试图在异步I/O框架中实现这一点,但似乎libpcap缺少一些响应(即,当它花费少于100 microsecondsTCP SYN和响应之间时,系列的第一个数据包).pcap句柄设置如下:

pcap_t* pcap = pcap_open_live(NULL, -1, false, -1, errorBuffer);
pcap_setnonblock(pcap, true, errorBuffer);
Run Code Online (Sandbox Code Playgroud)

然后我添加一个过滤器(包含在filterExpression字符串中):

struct bpf_program filter;
pcap_compile(pcap, &filter, filterExpression.c_str(), false, 0);
pcap_setfilter(pcap, &filter);
pcap_freecode(&filter);
Run Code Online (Sandbox Code Playgroud)

在循环中,在发送每个数据包之后,我使用select来知道我是否可以从libpcap读取:

int pcapFd = pcap_get_selectable_fd(pcap);
fd_set fdRead;
FD_ZERO(&fdRead);
FD_SET(pcapFd, &fdRead);
select(pcapFd + 1, &fdRead, NULL, NULL, &selectTimeout);
Run Code Online (Sandbox Code Playgroud)

阅读它:

if (FD_ISSET(pcapFd, &fdRead)) {
     struct pcap_pkthdr* pktHeader;
     const u_char* pktData;
     if (pcap_next_ex(pcap, &pktHeader, &pktData) > 0) {
         // Process received response.
     }
     else {
         // Nothing to receive (or …
Run Code Online (Sandbox Code Playgroud)

c++ asynchronous raw-sockets libpcap

6
推荐指数
1
解决办法
4132
查看次数

将一个函数元组应用于一个值并返回一个元组

现在,我有以下两个函数应用于一个值并返回一个2值元组:

template<typename F1, typename F2>
class Apply2
{
public:
    using return_type = std::tuple<typename F1::return_type, typename F2::return_type>;

    Apply2(const F1& f1, const F2& f2) : f1_(f1), f2_(f2) {}

    template<typename T> return_type operator()(const T& t) const
    {
        return std::make_tuple(f1_(t), f2_(t));
    }

protected:
    const F1& f1_;
    const F2& f2_;
};
Run Code Online (Sandbox Code Playgroud)

我想把它推广到N个函数:

template<typename ...F>
class ApplyN
{
public:
    using return_type = std::tuple<typename F::return_type...>;

    ApplyN(const std::tuple<F...>& fs) : functions_(fs) {}

    template<typename T> return_type operator()(const T& t) const
    {
        return ???;
    }

protected:
    std::tuple<F...> functions_;
};
Run Code Online (Sandbox Code Playgroud)

我知道我可能需要以某种方式使用模板递归,但我无法绕过它.有任何想法吗?

c++ tuples c++11

6
推荐指数
1
解决办法
399
查看次数

bad_weak_ptr在基类中调用shared_from_this()时

我有一个SuperParent类,一个Parent类(派生自SuperParent),并且都包含shared_ptr一个Child类(包含a weak_ptr到a SuperParent).不幸的是,我bad_weak_ptr在尝试设置Child指针时遇到异常.代码如下:

#include <boost/enable_shared_from_this.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>

using namespace boost;

class SuperParent;

class Child {
public:
    void SetParent(shared_ptr<SuperParent> parent)
    {
        parent_ = parent;
    }
private:
    weak_ptr<SuperParent> parent_;
};

class SuperParent : public enable_shared_from_this<SuperParent> {
protected:
    void InformChild(shared_ptr<Child> grandson)
    {
        grandson->SetParent(shared_from_this());
        grandson_ = grandson;
    }
private:
    shared_ptr<Child> grandson_;
};

class Parent : public SuperParent, public enable_shared_from_this<Parent> {
public:
    void Init()
    { …
Run Code Online (Sandbox Code Playgroud)

c++ boost weak-references shared-ptr

5
推荐指数
1
解决办法
4507
查看次数