小编Art*_*Art的帖子

复合文字生命周期和if块

这是一个理论问题,我知道如何明确地做到这一点,但我很好奇并且挖掘了标准,我需要第二对标准律师的眼睛.

让我们从两个结构和一个init函数开始:

struct foo {
    int a;
};
struct bar {
    struct foo *f;
};
struct bar *
init_bar(struct foo *f)
{
    struct bar *b = malloc(sizeof *b);
    if (!b)
        return NULL;
    b->f = f;
    return b;
}
Run Code Online (Sandbox Code Playgroud)

我们现在有一个草率的程序员不检查返回值:

void
x(void)
{
    struct bar *b;

    b = init_bar(&((struct foo){ .a = 42 }));
    b->f->a++;
    free(b);
}
Run Code Online (Sandbox Code Playgroud)

从我对标准的阅读中,除了可能解除引用NULL指针之外,这里没有任何错误.struct foo通过指针修改struct bar应该是合法的,因为发送到的复合文字的生命周期init_bar是包含它的块,这是整个函数x.

但现在我们有一个更细心的程序员:

void
y(void)
{
    struct bar *b;

    if ((b = init_bar(&((struct foo){ .a …
Run Code Online (Sandbox Code Playgroud)

c

18
推荐指数
1
解决办法
269
查看次数

是否可以将 bind() *this 绑定到类成员函数以对 C API 进行回调

有没有办法使用 boost 或 std bind() 以便我可以在 C API 中使用结果作为回调?这是我使用的示例代码:

#include <boost/function.hpp>
#include <boost/bind/bind.hpp>

typedef void (*CallbackType)();

void CStyleFunction(CallbackType functionPointer)
{
    functionPointer();
}

class Class_w_callback
{
public:
    Class_w_callback()
    {
        //This would not work
    CStyleFunction(boost::bind(&Class_w_callback::Callback, this));
    }
    void Callback(){std::cout<<"I got here!\n";};
};
Run Code Online (Sandbox Code Playgroud)

谢谢!

c++ boost std

4
推荐指数
1
解决办法
1497
查看次数

mmap 无效参数错误

这是我第一次使用 mmap 系统调用。我收到无效参数错误,我不明白为什么,显然我遗漏了一些东西,请帮助我,谢谢

#include <stdio.h>
#include <sys/mman.h>


int main() {

    long pageSize = getpagesize () ; 

    size_t length = 4096 ;


    int * map = (int * ) mmap ( 0 , length , PROT_READ | PROT_WRITE , MAP_ANONYMOUS , 0 , 0 ) ; 
        if ( map == MAP_FAILED ) {

            perror ( " error mapping " ) ;

        }

    return 0 ;
}
Run Code Online (Sandbox Code Playgroud)

c linux

3
推荐指数
1
解决办法
7894
查看次数

标签 统计

c ×2

boost ×1

c++ ×1

linux ×1

std ×1