How to solve the assignment problem of #c++# structure?

wei_kesong 注册会员
2023-02-27 16:40
diabloyq 注册会员
2023-02-27 16:40

Write based on Monster group and GPT: The
functions clone2 and clone3 both have problems.
In the function clone2, you create a temporary variable, newguy, and then assign the value of ft to newguy. However, newguy is destroyed after the function returns, so you cannot reference it as a return value. This can lead to undefined behavior.

In clone3, you create a pointer newguy to free_throws, but you don't allocate memory for newguy, which means it's undefined. When assigning the value of ft to *newguy, you may write the value to an unallocated memory location, which may also result in undefined behavior.

In the second code, you assign the return value of clone3 to ft_2, but you don't initialize ft_2, which means it contains undefined values. In assigning the return value of clone3 to ft_2, you copy the value of ft, but you do not allocate memory for ft_2, which may result in undefined behavior.

In the third piece of code, you first declare ft_2 and then assign the return value of clone3 to it. This ensures that ft_2 is initialized and that there is enough memory to store its value.

Therefore, if you want to use a function to initialize a structure, you should make sure to initialize the structure before allocating any memory, and take care to ensure that enough memory is allocated when using Pointers.

Proposed changes to clone2 and clone3 functions:

// 用引用返回结构体对象,避免拷贝,可以提高性能
const free_throws& clone2(const free_throws& ft) {
    // 直接使用初始化列表创建 newguy 对象
    free_throws newguy{ft.name};
    return newguy; // 返回对象的引用

// 用指针返回结构体对象,需要在堆上分配内存,并在适当的时候释放内存
free_throws* clone3(const free_throws& ft) {
    free_throws* newguy = new free_throws{ft.name}; // 在堆上分配内存
    return newguy; // 返回指针

When using the above functions, you need to be careful to release the memory allocated by the pointer returned by clone3 when appropriate to avoid memory leaks.

int main(){
    free_throws ft_{"abc"};
    cout << "ft_ address = " << &ft_ << endl;
    // 使用 clone2 函数
    const free_throws& ft_2 = clone2(ft_);
    cout << "ft2_ address = " << &ft_2 << endl;
    // 使用 clone3 函数
    free_throws* ft_3 = clone3(ft_);
    cout << "ft3_ address = " << ft_3 << endl;
    delete ft_3; // 释放内存
    return 0;

The advantage of using references to return objects is that the code is simple and easy to use. The advantage of using Pointers to return objects is flexibility, allowing you to freely control the allocation and release of memory.

About the Author

Question Info

Publish Time
2023-02-27 16:40
Update Time
2023-02-27 16:40