引用结构

Reference to a Structure

我从一本名为 C++ Primer Plus 的书中读到这部分内容(第 400 页。Chapter:8 - 函数历险记)

A second method is to use new to create new storage. You've already seen examples in which new creates space for a string and the function returns a pointer to that space. Here's how you chould do something similar with a referece:

const free_throws & clone(free_throw & ft)
{
    free_throws * ptr;
    *ptr = ft;
    return *ptr;
}

The first statement creates a nameless free_throw structure. The pointer ptr points to the structure, so *ptr is the structure. The code appears to return the structure , but the function declaration indicates that the function really reutrns a reference to this structure. You could use this function this way:

free_throw & jolly = clone(three);

This makes jolly a reference to the new structure. There is a problem with this approach: YOu should use delete to free memory allocated by new when the memory is no longer needed. A call to clone() conceals the call to new, making it simpler to forget to use delete later.

我的疑惑:

据我所知,对于最佳实践,你不应该在没有初始化指针的情况下取消引用指针,并且声明指向某个结构的指针只会为指针分配 space 而不是为整个结构分配,你必须分配space 分别为结构。 根据这本书,声明一个指针会自动将 space 分配给整个结构,并且指针在没有初始化的情况下被取消引用。 调用函数时如何自动调用new运算符?

As far as I know for best practices you should never dereference a pointer without initializing it

这不仅是“最佳做法”,而且绝对不能这样做。您绝不能通过未初始化的指针间接访问。

How the new operator is automatically called when calling the function ?

new 运算符未被调用。


free_throws * ptr;

The first statement creates a nameless free_throw structure.

这是完全错误的。第一条语句创建一个指针,根本没有结构的实例。引用的文本与代码不匹配。

free_throw & jolly = clone(three);

This makes jolly a reference to the new structure.

这也是错误的。 clone returns 对 const 的引用,对非常量 jolly 的引用不能绑定到它。此初始化格式错误。


我会假设代码是错误的,并且有意在其中使用new,但作者忘记了。要理解的最重要的部分是第三个引用,它解释了函数有问题;因此,即使该功能已“固定”为可能按预期使用 new,该功能也无用。