'Overwrite elements in std::shared_ptr to array, what got wrong?
I have following header :
#ifndef MY_TEMPLATE_CLASSES_H
#define MY_TEMPLATE_CLASSES_H
#pragma once
#include <cstdio>
#include <iostream>
#include <memory>
template <typename T, size_t N> class Array {
private:
std::shared_ptr<T[]> ptr;
public:
explicit Array(const T arr[N]);
void print();
};
template <typename T, size_t N> Array<T, N>::Array(const T arr[N]) {
ptr = std::make_shared<T[]>(N);
for (size_t i = 0; i < N; ++i) {
ptr[i] = arr[i];
}
}
template <typename T, size_t N> void Array<T, N>::print() {
for (size_t i = 0; i < N; ++i)
std::cout << &ptr[i] << ":" << ptr[i] << " ";
std::cout << std::endl;
}
#endif // MY_TEMPLATE_CLASSES_H
and the main file:
#include "my_template_classes.hpp"
#include <variant>
// C++17 at least
#if (__cplusplus < 201703L)
//# error " You should compile with -std=C++17"
#endif
using namespace std;
int main() {
static_assert(__cplusplus >= 201703L,
"This file expects a C++17 compatible compiler.");
// create template class
int arr[5] = {1, 2, 3, 4, 5};
Array<int, 5> a(arr);
a.print();
return 0;
}
the output is: 0x12a9ee0:1 0x12a9ee4:2 0x12a9ee8:3 0x12a9eec:4 0x12a9ef0:842102832
compiled with g++ (GCC) 8.5.0 20210514 (Red Hat 8.5.0-12)
Why the last element in address 0x12a9ef0 is not 5?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
