关于weakref的用法

在《程序员的自我修养—链接、装载、库》这本书的3.5.5节,讲到了一个知识点:weakref,弱引用。

书中在第93页举出的例子发现编译不通过,报错。

__attribute__((weakref)) void foo();

int main()
{
	foo();
}
关于weakref的用法_第1张图片

据网络文档介绍,有四种weakref的用法,我自己试验下来只有三种,还有一种一直报错,没懂怎么用。

int y()
{
	return 0;
}

/*
可以这么声明但是不能调用,会报错
*/
int x1() __attribute__ ((weakref));

/*
可以调用
函数必须是static
int x() __attribute__ ((weakref ("y")));这样会报错
*/
static int x2() __attribute__ ((weakref ("y")));

/*
可以调用
需要定义y函数,可以去除static属性
*/
static int x3() __attribute__ ((alias ("y")));

int main()
{
	x2();
	x3();
	return 0;
}
书中举出的例子,写法没错,但错就错在它在函数中调用了这个弱引用,如果不调用就不会报错了。关于这个调用,还有一个,网上很多解决方法是将weakref改成weakref,也就是下面这样

__attribute__((weak)) void foo();
这种方法也可以在有函数中调用该函数的情况下,编译通过。文档也有提到,当weakref没有参数时和weak相同,但个人不推荐这种写法。

此外,alias和weakref("argument")这两种写法都是类似于找个备胎,如果这个函数没定义,就用备用的。

weakref1.c

#include 
void fun2()
{
	printf("this is fun2\n");
}
weakref.c

static __attribute__((weakref("fun2")))void fun1();
int main()
{
	fun1();
	return 0;
}
此时实际输出的是函数fun2的内容。

如果fun1已经有了定义,则输出fun1的内容。前提是fun1的声明/定义要在fun2之前。

另外有一种报错的写法是下面这样子的:

static int x() __attribute__ ((weak, weakref, alias ("y")));
这个写法,不管是不是把static属性去掉,都会报错。


这个用法还没搞明白。


下面是网上找的关于weakref用法的一些说明。

weakref
weakref ("target")
The weakref attribute marks a declaration as a weak reference. Without arguments, it should be accompanied by an alias attribute naming the target symbol. Optionally, the target may be given as an argument to weakref itself. In either case, weakref implicitly marks the declaration as weak. Without a target, given as an argument to weakref or to alias, weakref is equivalent to weak.

static int x() __attribute__ ((weakref ("y")));
/* is equivalent to... */
static int x() __attribute__ ((weak, weakref, alias ("y")));
/* and to... */
static int x() __attribute__ ((weakref));
static int x() __attribute__ ((alias ("y")));
A weak reference is an alias that does not by itself require a definition to be given for the target symbol. If the target symbol is only referenced through weak references, then it becomes a weak undefined symbol. If it is directly referenced, however, then such strong references prevail, and a definition is required for the symbol, not necessarily in the same translation unit.

The effect is equivalent to moving all references to the alias to a separate translation unit, renaming the alias to the aliased symbol, declaring it as weak, compiling the two separate translation units and performing a reloadable link on them.

At present, a declaration to which weakref is attached can only be static.
这是网页源地址 点击打开链接。




你可能感兴趣的:(C++基础编程,程序员的自我修养)