Reputation: 2214
summary: to use boost::scoped_ptr with char* data type. I have written my own Str class and function based on Accelerated C++ chap12. Everything works good but just for my curiosity purpose I tried to use boost::scoped_ptr but After spending hours I made no success.
To be noted: If I dont use boost ptr everything works as expected.
Issue::error: no matching constructor for initialization of 'boost::scoped_ptr' boost::scoped_ptr< char* > buffer_smrt_ptr( buffer ); ^ ~~~~~~
Below are my code
// test of copy function
Str test_cpy( "String copy test");
char* buffer = new char[ test_cpy.size() ];
boost::scoped_ptr< char* > buffer_smrt_ptr( buffer );
Str::size_type n_len = test_cpy.copy( buffer_smrt_ptr,10, 0);
buffer_smrt_ptr[ n_len ] = '\0';
printf( "your copied string: == %s\n", buffer );
Upvotes: 0
Views: 1075
Reputation: 48457
The error you encounter results from the following declaration-initialization mismatch:
boost::scoped_ptr< char* > buffer_smrt_ptr( buffer );
// ^
That is, when declaring the <T>
type of boost::scoped_ptr<T>
, it is not the type of a pointer to the stored value, but the type of the pointed value itself. Hence, the asterisk is redundant and should be removed.
However, for storing pointers to dynamically allocated arrays and accessing their value through operator[]
one should use boost::scoped_array<T>
instead:
Str test_cpy( "String copy test" );
char* buffer = new char[ test_cpy.size() ];
boost::scoped_array< char > buffer_smrt_ptr( buffer );
// ^^^^^ ^^^^
Additionally, boost::scoped_ptr<T>
(as well as boost::scoped_array<T>
) is a non-copyable type, if you aim to pass it to the Str::copy()
member function either catch it by reference OR get a raw pointer:
Str::size_type n_len = test_cpy.copy(buffer_smrt_ptr.get(), 10, 0);
// ^^^^^^
Going further, if your test_cpy.size()
member function returns a string length without a trailing \0
, you probably need to increase the buffer by one more character:
char* buffer = new char[ test_cpy.size() + 1 ];
// ^^^
Upvotes: 5
Reputation: 10959
You should use boost::scoped_array
instead of boost::scoped_ptr
. It is smart pointer for managing array. Also its template type should be char
instead of char*
. I think your compiler error is because of second issue.
Upvotes: 2