Best practice for std :: auto_ptr

I'm just used to smart pointers using std :: auto_ptr.

Suppose I want to call a function using auto_ptr and regular pointers.

auto_ptr<uint32> data_smart(new uint32[123])]);
uint32 data_fix[123];
uint32* data_dumb = new uint32[123];

processData(data_smart);
processData(data_fix);
processData(data_dumb);

What is the best practice for this without overloading? Having a processData function with uint32 * argument? Can I use a smart uint32 * pointer for this case with .get ()? Or how am I supposed to do this? Thanks in advance!

+3
source share
8 answers

In your situation, using a vector is the safest choice:

std::vector<uint32> data(123);

Signatures of the Data process should ideally be:

void processData(const std::vector<uint32> & data);

However, this is more commonly used:

void processData(uint32 * bytes, int length);

In both cases, you can use a vector:

// 1
processData(data);

// 2
processData(data.data(), data.size());
0
source

1.

auto_ptr<uint32> data_smart(new uint32[123])]);

. auto_ptr ( delete, delete[]).

2.  auto_ptr , , , ( ), . :

processData(data_smart.get());

, data_smart .

+5

EDIT: - , , ....


... ...

, , , .

uint32 * ?

. std::auto_ptr<t>::get().

+1

, auto_ptr . , . std:: auto_ptr .

std:: auto_ptr, , , std:: auto_ptr . , auto_ptr (data_smart) processData, data_smart .

, , boost::scoped_array boost:: shared_array.

+1

auto_ptr. ++ 0x std::unique_ptr (: ++ 0x Draft Standard, D, 10). std::tr1::shared_ptr boost::scoped_ptr.

- , . boost::shared_array .

. , , , std::vector std::vector ( std::array , ). , :

std::vector<uint32> dataVector;
data.reserve(123);

// or, if the size is always 123:
std::tr1::array<uint32, 123> dataArray;

, - uint32*, vector std::tr1::array , C-style:

processData(&dataVector[0]);
processData(dataArray.data());

, . processData :

processData(&dataVector[0], dataVector.size());

/ C-, :

void processData(std::vector<uint32>& data) {
    // process the data
}

// call it like this:
processData(dataVector);

vector s, std::tr1::array . , , , :

template <class AnIterator>
void processData(AnIterator begin, AnIterator end) {
    for (AnIterator it = begin; it != end; ++it) {
        // process each item
    }
}

// call it like this
processData(dataVector.begin(), dataVector,end());

// or like this
processData(dataArray.begin(), dataArray.end());

// or even like this (assume c_data is a C-style array):
processData(c_data, c_data + number_of_items_in_c_data);

, C .

+1

, data_smart . , , auto_ptr delete , delete[], UB ( , data_dumb).

, auto_ptr , .

. -, , . , auto_ptr::get(), .

0

HAMMERED auto_ptr .

?

, , ?

processData uint32 *?

processData( uint32* ) , , , .
processData( uint32[123] ), (123 ).
processData( uint32 &[123] ) ref const.

uint32 * .get()?

, get(), "", .

: , , , , - -.

0

Source: https://habr.com/ru/post/1779684/


All Articles