You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Traveler类display方法异常:姓名和目的地显示乱码求助

Troubleshooting: Garbled Name/Destination in Last Traveler Instance's display()

Hey there, let's break down why your last Traveler instance is showing garbled text for name and destination while the date displays correctly. This is a super common pitfall in C++ related to dynamic memory and default copy behavior—let's dig into it:

Most Likely Root Cause: Shallow Copy from Default Class Functions

If your Traveler class uses char* to store name and destination but doesn't implement custom copy constructor and assignment operator logic, you're hitting a shallow copy problem. Here's the play-by-play:

When you add Traveler objects to a list (like an array or std::vector), the compiler uses auto-generated default copy functions. These functions only copy the pointer addresses, not the actual string data the pointers point to. This means multiple Traveler instances end up sharing the same heap memory blocks for name and destination.

For example, if your class looks something like this:

#include <cstring>

class Traveler {
private:
    char* name;
    char* destination;
    Date travelDate; // Assume Date is a value-type struct/class
public:
    // Constructor allocates heap memory for strings
    Traveler(const char* n, const char* dest, Date d) {
        name = new char[strlen(n) + 1];
        strcpy(name, n);
        destination = new char[strlen(dest) + 1];
        strcpy(destination, dest);
        travelDate = d;
    }

    // Destructor frees the heap memory
    ~Traveler() {
        delete[] name;
        delete[] destination;
    }

    // display() method implementation
    void display() const {
        printf("%s goes to %s on %04d/%02d/%02d\n", name, destination, 
               travelDate.year, travelDate.month, travelDate.day);
    }

    // No custom copy constructor/assignment operator defined
};

When you populate your list (e.g., std::vector<Traveler> travelers; travelers.push_back(Traveler(...));), the temporary Traveler object gets copied into the vector, then destroyed. The destructor frees the heap memory for name and destination, leaving the vector's copy with pointers to already released memory. When you call display() on the last instance, you're accessing invalid memory—hence the garbled text. The date works because it's a value type (copied directly, no shared pointers involved).

Proven Fixes to Resolve the Issue

1. Implement Deep Copy with Custom Copy Functions

Add these to your Traveler class to ensure copies duplicate the actual string data instead of just pointers:

// Copy Constructor
Traveler(const Traveler& other) {
    // Allocate new memory and copy name data
    name = new char[strlen(other.name) + 1];
    strcpy(name, other.name);
    // Repeat for destination
    destination = new char[strlen(other.destination) + 1];
    strcpy(destination, other.destination);
    // Copy date (safe, since it's a value type)
    travelDate = other.travelDate;
}

// Assignment Operator (using copy-swap idiom for safety)
Traveler& operator=(Traveler other) {
    std::swap(name, other.name);
    std::swap(destination, other.destination);
    std::swap(travelDate, other.travelDate);
    return *this;
}

2. Use std::string Instead of char*

The simplest fix is to let the C++ standard library handle memory management for you. Replace char* with std::string:

#include <string>
#include <iostream>

class Traveler {
private:
    std::string name;
    std::string destination;
    Date travelDate;
public:
    // Simplified constructor with initializer list
    Traveler(const std::string& n, const std::string& dest, Date d)
        : name(n), destination(dest), travelDate(d) {}

    // Updated display() method using std::string
    void display() const {
        std::cout << name << " goes to " << destination << " on "
                  << travelDate.year << "/" << travelDate.month << "/" << travelDate.day << "\n";
    }

    // No need for custom destructor/copy functions—compiler generates safe versions automatically!
};

Additional Checks If the Fixes Don't Work

If you still see garbled text, double-check these edge cases:

  • List creation logic: Are you adding local objects that get destroyed before you call display()?
  • display() implementation: Are you using correct format specifiers (e.g., don't mix %s with std::string)?
  • Date class implementation: While it's working, ensure it doesn't have hidden memory issues (though this is unlikely to affect name/destination).

内容的提问来源于stack exchange,提问作者sarcus904

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:25:02