Skip to content

[cpp,c++ std::copy]How to copy pointer(address) with std::copy (why you should use std::copy instead of memcpy)

How to copy pointer(address) with std::copy

(aka. why you should use std::copy instead of memcpy)

std::copy

cppreference.com:

Copies the elements in the range, defined by [first, last), to another range beginning at d_first.

std::copy can be used to not only copy container data, but also memory and pointer address

Using std::copy to copy container data.

Using std::copy to copy memory.

Using std::copy to copy pointer address.

How to copy pointer using std::copy

A pointer is nothing else but an integral variable, which has its own address and value. The value that the pointer variable holds is the address of another variable or object. The address of the pointer itself can be taken, and given to another pointer as its value holded too.

It's a good idea to replace memcpy with std::copy, and replace memset with std::fill.

The following c++ example demonstrates how to copy the pointer value (the address of another variable or object it holds) to another nullptr pointer, then the nullptr pointer becomes useful.

#include <algorithm>
#include <vector>
#include <iostream>
#include <boost/assert.hpp>

class cpp_class
{
public:
    double x;
    std::string str;
};

int main()
{
    cpp_class obj{1.234, "hello c++"};
    auto * ptr = &obj; // Pointer ptr holds the address of obj.
    
    std::uint64_t x;
    // Copy the pointer value to variable x as std::uint64_t
    std::copy_n(reinterpret_cast<std::uint64_t *>(&ptr), 1, &x);
    
    cpp_class * ptr2 = nullptr; // Declare a pointer and inited with nullptr
    
    // Now, copy the value of x to the nullptr pointer ptr2
    std::copy_n(&x, 1, reinterpret_cast<std::uint64_t *>(&ptr2));
    // See! You can assert that the value of ptr2 equals to the address of obj
    BOOST_ASSERT(ptr2 == &obj);
    
    // Valid!
    BOOST_ASSERT(ptr2->x == 1.234);
    // Valid!
    BOOST_ASSERT(ptr2->str == "hello c++");
    
    std::cout << ptr2->str >> std::endl; // hello c++
}

 

 

 

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

Add Comment

E-Mail addresses will not be displayed and will only be used for E-Mail notifications.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Form options

Submitted comments will be subject to moderation before being displayed.

@cppfx.xyz