以下代码编译时在VSC++2017中没有任何错误,也没有在gcc 7.3.0 (error: invalid static_cast from type ‘int(int)’ to type ‘void*’ void* p = static_cast<void*>(func))中编译
#include <iostream>
int func(int x) { return 2 * x; }
int main() {
void* p = static_cast<void*>(func);
return 0;
}
下面是这段代码:
void a() { }
// function parameter first defined as function, then as pointer to function
void g(void f() = a, void (*d)() = a) {
}
int main(){
void (*z)() = a; // works ok
//void z() = a; error: illegal initializer (only variables can be initialized)
return 0;
}
在函数参数列表中,可以将函数参数
我有一个关于void*和void**的问题,我知道这是一个古老的问题,以前在stackoverflow中已经(有点)被问过了。所以问题是这样的:
当我在ubuntu 10.10下用gcc 4.4.3编译这段代码时,我得到了以下警告:
zz.c: In function ‘main’:
zz.c:21: warning: passing argument 1 of ‘bar’ from incompatible pointer type
zz.c:9: note: expected ‘void **’ but argument is of type ‘float **’
为什么可以将变量x作为f
下面的代码试图使用void (即不进行转换)将一个memcpy指针存储在不同类型的指针中,然后恢复原始的void指针。它会调用未定义的行为吗?
#include <assert.h>
#include <string.h>
#include <stdio.h>
int main()
{
// Ensure that an int pointer is large enough to store a void pointer
_Static_assert( sizeof( int* ) >= sizeof( void* ) );
我的代码在c和c++中的行为是不同的。
void *(*funcPtr)() = dlsym(some symbol..) ; // (1) works in c but not c++
int (*funcPtr)();
*(void**)(&funcPtr) = dlsym(some symbol..) ; // (2) works in c++
我不明白为什么第二次铸造工作在c++,而第一次铸造不工作在c++。在c++中,(1)显示的错误消息从void*到void*()的转换是无效的。
如果我写
int zero = 0;
void *p1 = (void *)0;
void *p2 = (void *)(int)0;
void *p3 = (void *)(0 /*no-op, but does it affect the next zero?*/, 0);
void *p4 = (void *)zero; // For reference, this is a pointer to address zero
void *p5 = 0; // For reference, this is a null pointer
void *p6
int main()
{
int a;
void *p;
p = &a;
printf("%ld\n",(long)p);
p = p+1;
printf("%ld\n",(long)p);
}
在这个程序中,p+1只是将p的值递增1。我知道void pointer arithmetic在C中是不可能的,所以GCC隐式地执行了。如果是,那么它是否将其视为char pointer。另外,为什么dereferencing不能用于空指针,如果它隐式地执行指针运算。
我正在尝试更改当前的设计,并希望使用智能指针(最好是unique_ptr,如Herb Sutter所说,在怀疑时,默认情况下更喜欢unique_ptr ),但我感到困惑的是,在当前的设计中,一个指针将被传递给多个类。
示例代码如下所示
class X {
private:
ZHandler* _mZHandler; //change it as unique_ptr or shared_ptr??
public:
X()
{
Z* zPtr = createUsingFactory(); // instantiated by legacy code fa
我正在试图理解下面的片段中发生了什么:
// using FUN = void(*)(void);
using FUN = void(void);
template<FUN fun> struct Fun{};
int main ()
{
FUN fun;
Fun<fun>{};
}
我可以用void(void)作为函数的非类型参数,一切都很好,程序编译.但是,将类型更改为指针为函数,即删除第一行中的注释并注释第二行,就会导致错误。
(g++)错误:“乐趣”的值在常量表达式中不可用
(clang)错误:类型为‘’的非类型模板参数(又名'vo
情况就是这样。我使用的是一个库(GLFW),它具有您设置的一些回调函数,用于接收有关各种内容(错误、窗口大小更改等)的通知。这些函数必须是静态的。为了将这些数据返回到类的“非静态”实例,我被迫使它们成为一个单例。是否有更好/替代的方法来处理类中的强制静态函数?
到目前为止,我想出的最好的是:
//OpenGlTest.h
#pragma once
#include "glfw.h"
#pragma comment(lib,"opengl32.lib")
#pragma comment(lib,"glfw3dll.lib")
class Op