Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

smart pointers-to-char replacing strings

70 views
Skip to first unread message

Paul

unread,
Feb 1, 2015, 6:22:30 PM2/1/15
to
I am trying to rewrite text-handling code involving char* and const char* in terms of boost::scoped_array<char>

Could someone possibly provide a reference to this topic?

For example, the following function is wrong, and I don't really know why.
boost::scoped_array<char> get(const char *s)
{
int size = std::strlen(s);
boost::scoped_array<char> text(new char[size]);
for(int i = 0; i < size; i++)
text[i] = s[i];

return text;
}


I'm sure I just need to read up on it but google searches didn't seem to broach this topic.

Many thanks.

Paul

Ian Collins

unread,
Feb 1, 2015, 6:38:09 PM2/1/15
to
Paul wrote:
> I am trying to rewrite text-handling code involving char* and const char* in terms of boost::scoped_array<char>

What's wrong with std::string?

--
Ian Collins

Paul

unread,
Feb 1, 2015, 8:00:15 PM2/1/15
to
Thanks for your reply.
I'm trying to solve a problem from a boost book. (No, it's not homework for an academic course). Please don't give too much help.

The problem is below:

Optimize the following program by using an appropriate smart pointer.

#include <iostream>
#include <cstring>

char *get(const char *s)
{
int size = std::strlen(s);
char *text = new char[size + 1];
std::strncpy(text, s, size + 1);
return text;
}

void print(char *text)
{
std::cout << text << std::endl;
}

int main(int argc, char *argv[])
{
if (argc < 2)
{
std::cerr << argv[0] << " <data>" << std::endl;
return 1;
}

char *text = get(argv[1]);
print(text);
delete[] text;
}

Nobody

unread,
Feb 3, 2015, 6:58:32 AM2/3/15
to
On Sun, 01 Feb 2015 15:22:17 -0800, Paul wrote:

> For example, the following function is wrong, and I don't really know why.
> boost::scoped_array<char> get(const char *s)
> {
> int size = std::strlen(s);
> boost::scoped_array<char> text(new char[size]);
> for(int i = 0; i < size; i++)
> text[i] = s[i];
>
> return text;
> }

1. You aren't copying (or even allocating space for) the terminating null
byte.

2. boost::scoped_array is non-copyable, but the "return" statement
makes a copy.

0 new messages