CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Aug 2000
    Posts
    1,471

    an auto_ptr question

    I declared:
    auto_ptr<char> a(new char[20]);

    My question is how I can initialize a with a string?

  2. #2
    Join Date
    Oct 2002
    Location
    Tx, US
    Posts
    208
    Hi,
    U need to call explicitaly strcpy to copy a string.
    u can not initialize it directly.

    Vinod

  3. #3
    Join Date
    Aug 2000
    Posts
    1,471
    Originally posted by vinodp
    Hi,
    U need to call explicitaly strcpy to copy a string.
    u can not initialize it directly.

    Vinod
    I am sorry I don't understand what you said. Actually, strcpy doesn't take the auto_ptr<char> as a parameter type. So how could you use strcpy to copy a string to a in question?

  4. #4
    Join Date
    Oct 2002
    Location
    Tx, US
    Posts
    208
    strcpy(a.get(), "Codeguru");
    Beware of length of the string & allocated char length.
    My suggestion is instead of this use STL::string class.

    Vinod

  5. #5
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721
    Code:
    auto_ptr<char> a(new char[20]);
    auto_ptr can not be used for arrays. It calls delete,
    not delete [] on the object it owns.

    Use one of the standard containers (std::string as
    already suggested or something like :

    vector<char> a(20);

    then if you need to pass to a function that expects a c-style
    string, you use : &a[0]

  6. #6
    Join Date
    Aug 2000
    Posts
    1,471
    Originally posted by vinodp
    strcpy(a.get(), "Codeguru");
    Beware of length of the string & allocated char length.
    My suggestion is instead of this use STL::string class.

    Vinod
    I don't think strcpy(a.get(), "Codeguru") is going to work.

  7. #7
    Join Date
    Aug 2000
    Posts
    1,471
    Originally posted by Philip Nicoletti
    Code:
    auto_ptr<char> a(new char[20]);
    auto_ptr can not be used for arrays. It calls delete,
    not delete [] on the object it owns.

    Use one of the standard containers (std::string as
    already suggested or something like :

    vector<char> a(20);

    then if you need to pass to a function that expects a c-style
    string, you use : &a[0]
    I guess you are right. One way is like this:
    auto_ptr<string> a(new string("Hello\n");

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured