Explaining pointers to a Javascript developer - pointers

I started to learn coding backwards: high level first. This has the obvious liability of missing some basic concepts that I should definitely know, and when I try to learn a low level language, it throws me.
I have tried many times to understand pointers, however the explanations rapidly go over my head, usually because all of the example code uses languages that use pointers, which I don't understand other things about, and then I spin.
I am the most (and very at that) fluent in Javascript.
How would you explain pointers to a sad Javascript developer like me? Could someone provide me a practical, real life example?
Maybe even showing how, if Javascript had pointers, you could do x, and a pointer is different than a raw variable because of y.

Here's an attempt at a self-contained answer from first principles.
Pointers are part of a type system that permit the implementation of reference semantics. Here's how. We suppose that our language has a type system, by which every variable is of a certain type. C is a good example, but many languages work like this. So we can have a bunch of variables:
int a = 10;
int b = 25;
Further, we assume that function arguments are always copied from the caller scope into the function scope. (This is also true for many real languages, though the details can quickly become subtle when the type system gets 'hidden' from the user (e.g. such as in Java)). So let's have a function:
void foo(int x, int y);
When calling foo(a, b), the variables a and b are copied into local variables x and y corresponding to the formal parameters, and those copies are visible within the function scope. Whatever the function does with x and y has no effect on the variables a and b at the call site. The entire function call is opaque to the caller.
Now let's move on to pointers. A language with pointers contains, for every object type T, a related type T *, which is the type "pointer to T". Values of type T * are produced by taking the address of an existing object of type T. So a language that has pointers also needs to have a way to produce pointers, which is "taking the address of something". The purpose of a pointer is to store the address of an object.
But that's only one half of the picture. The other half is what to do with the address of an object. The main reason for caring about the address of an object is to be able to refer to the object whose address is being stored. This object is obtained by a second operation, suitably called dereferencing, which when applied to a pointer produces the object which is being "pointed to". Importantly, we do not a copy of the object, but we get the actual object.
In C, the address-of operator is spelled &, and the dereference operator is spelled *.
int * p = &a; // p stores the address of 'a'
*p = 12; // now a == 12
The first operand of the final assignment, *p, is the object a itself. Both a and *p are the same object.
Now why is this useful? Because we can pass pointers to functions to allow functions to change things outside the function's own scope. Pointers allow for indirection, and thus for referencing. You can tell the function about "something else". Here's the standard example:
void swap(int * p, int * q)
{
int tmp = *p;
*p = *q;
*q = tmp;
}
We can tell the function swap about our variables a and b by giving it the addresses of those variables:
swap(&a, &b);
In this way, we are using pointers to implement reference semantics for the function swap. The function gets to refer to variables elsewhere and can modify them.
The fundamental mechanism of reference semantics can thus be summarized thus:
The caller takes the address of the object to be refered to:
T a;
mangle_me(&a);
The callee takes a pointer parameter and dereferneces the pointer to access the refered value.
void mangle_me(T * p)
{
// use *p
}
Reference semantics are important for may aspects of programming, and many programming languages supply them in some way or another. For example, C++ adds native reference support to the language, largely removing the needs for pointers. Go uses explicit pointers, but offers some notational "convenience" by sometimes automagically dereferencing a pointer. Java and Python "hide" pointer-ness inside their type system, e.g. the type of a variable is in some sense a pointer to the type of the object. In some languages, some types like ints are naked value types, and others (like lists and dictionaries) are "hidden-pointer-included" reference types. Your milage may vary.

C++ rules are fairly simple and consistent. I actually find how Javascript handles object references and prototypes way more unintuitive.
Preface A: Why is Javascript A Bad Place To Start?
The first thing you need to fundamentally understand before you can tackle pointers is variables. You need to know what they are and how the computer keeps track of them.
Coming from a Javascript background you are used to every variable assigned to an object being a reference. That is, two variables can reference the same object. This is essentially pointers without any syntax to allow for more intricate use. You are also used to implicit copies of "basic" types like numbers. That is to say:
var a = MyObject;
var b = a;
Now if you change b you also change a. You would need to explicitly copy MyObject in order to have two variables pointing to different instances of it!
var a = 5;
var b = a;
Now if you change b, a is not actually changed. This is because assigning a to b when a is a simple type will copy it automatically for you. You cannot get the same behavior as objects with simple numbers and vise versa, so when you want two variables to refer to the same number you have to wrap it in an object. There is no explicit way to indicate how you want to handle references vs copies for primitive types.
You can see this inconsistent behavior with no variation on syntax (but an extreme variation on behavior) can make the relationship between variables and what they contain muddy. For this reason I highly suggest banishing this mental model for a moment as we continue on our journey to understand explicit pointers.
Preface B: YOLO: Variable Lifetime On The Stack
So, let's talk from here on out in C++ terms. C++ is one of the most explicit languages in terms of what a variable is vs a pointer. C++ is a good entry point because it is low level enough to talk in terms of memory and lifespan, but high level enough to understand things at a decent level of abstraction.
So, in C++ when you create any variable it exists in a certain scope. There are two ways to create a variable, on the stack, and on the heap.
The stack refers to the call stack of your application. Every brace pair pushes a new context onto the stack (and pops it when it runs out). When you create a local variable, it exists in that particular stack frame, when that stack frame is popped the variable is destroyed.
A simple example of scope:
#include <iostream>
#include <string>
struct ScopeTest{
ScopeTest(std::string a_name):
name(a_name){
std::cout << "Create " << name << std::endl;
}
~ScopeTest(){
std::cout << "Destroy " << name << std::endl;
}
ScopeTest(ScopeTest &a_copied){
std::cout << "Copy " << a_copied.name << std::endl;
name = a_copied.name + "(copy)";
a_copied.name += "(original)";
}
std::string name;
};
ScopeTest getVariable(){ //Stack frame push
ScopeTest c("c"); //Create c
return c; //Copy c + Destroy c(original)
}
int main(){
ScopeTest a("a"); //Create a
{
ScopeTest b("b"); //Create b
ScopeTest d = getVariable();
} //Destroy c(copy) + Destroy b
} //Destroy a
Output:
Create a
Create b
Create c
Copy c
Destroy c(original)
Destroy c(copy)
Destroy b
Destroy a
This should illustrate explicitly how a variable ties its life to the stack, how it is copied around, and when it dies.
Preface C: YOLO Variable Lifetime on the Heap
So, that's interesting conceptually, but variables can also be allocated outside of the stack, this is called "heap" memory because it is largely structure-less. The issue with heap memory is that you don't really have automatic cleanup based on scope. So you need a way to tie it to some kind of "handle" to keep track of it.
I'll illustrate here:
{
new ScopeTest("a"); //Create a
} //Whoa, we haven't destroyed it! Now we are leaking memory!
So, clearly we can't just say "new X" without keeping track of it. The memory gets allocated, but doesn't tie itself to a lifespan so it lives forever (like a memory vampire!)
In Javascript you can just tie it to a variable and the object dies when the last reference to it dies. Later I'll talk about a more advanced topic in C++ which allows for that, but for now let's look at simple pointers.
In C++ when you allocate a variable with new, the best way to track it is to assign it to a pointer.
Preface D: Pointers and The Heap
As I suggested, we can track allocated memory on the heap with a pointer. Our previous leaky program can be fixed like so:
{
ScopeTest *a = new ScopeTest("a"); //Create a
delete a; //Destroy a
}
ScopeTest *a; creates a pointer, and assigning it to a new ScopeTest("a") gives us a handle we can actually use to clean up and refer to the variable which exists in heap memory. I know heap memory sounds kinda confusing, but it's basically a jumble of memory that you can point to and say "hey you, I want a variable with no lifespan, make one and let me point at it".
Any variable created with the new keyword must be followed by exactly 1 (and no more than 1) delete or it will live forever, using up memory. If you try to delete any memory address other than 0 (which is a no-op) more than one time, you could be deleting memory not under your program's control which results in undefined behavior.
ScopeTest *a; declares a pointer. From here on out, any time you say "a" you are referring to a specific memory address. *a will refer to the actual object at that memory address, and you can access properties of it (*a).name. a-> in C++ is a special operator that does the same thing as (*a).
{
ScopeTest *a = new ScopeTest("a"); //Create a
std::cout << a << ": " << (*a).name << ", " << a->name << std::endl;
delete a; //Destroy a
}
Output for the above will look something like:
007FB430: a, a
Where 007FB430 is a hex representation of a memory address.
So in the purest sense, a pointer is literally a memory address and the ability to treat that address as a variable.
The Relationship Between Pointers and Variables
We don't just have to use pointers with heap allocated memory though! We can assign a pointer to any memory, even memory living on the stack. Just be careful your pointer doesn't out-live the memory it points to or you'll have a dangling pointer which could do bad things if you continue to try and use it.
It is always the programmer's job to make sure a pointer is valid, there are literally 0 checks in place in C++ to help you out when dealing with bare memory.
int a = 5; //variable named a has a value of 5.
int *pA = &a; //pointer named pA is now referencing the memory address of a (we reference "a" with & to get the address).
Now pA refers to the same value as &a, that is to say, it is the address of a.
*pA refers to the same value as a.
You can treat *pA = 6; the same as a = 6. Observe (continuing from the above two lines of code):
std::cout << *pA << ", " << a << std::endl; //output 5, 5
a = 6;
std::cout << *pA << ", " << a << std::endl; //output 6, 6
*pA = 7;
std::cout << *pA << ", " << a << std::endl; //output 7, 7
You can see why *pA is called a "pointer". It is literally pointing to the same address in memory as a. So far we have been using *pA to de-reference the pointer and access the value at the address it points to.
Pointers have a few interesting properties. One of those properties is that it can change the object it is pointing at.
int b = 20;
pA = &b;
std::cout << *pA << ", " << a << ", " << b << std::endl; //output 20, 7, 20
*pA = 25;
std::cout << *pA << ", " << a << ", " << b << std::endl; //output 25, 7, 25
pA = &a;
std::cout << *pA << ", " << a << ", " << b << std::endl; //output 7, 7, 25
*pA = 8;
std::cout << *pA << ", " << a << ", " << b << std::endl; //output 8, 8, 25
b = 30;
pA = &b;
std::cout << *pA << ", " << a << ", " << b << std::endl; //output 30, 8, 30
So you can see that a pointer is really just a handle to a point in memory. This can be exceptionally useful in many cases, do not write it off just because this sample is simplistic.
Now, the next thing you need to know about pointers is that you can increment them as long as the memory you are incrementing to belongs to your program. The most common example is C strings. In modern C++ strings are stored in a container called std::string, use that, but I will use an old C style string to demonstrate array access with a pointer.
Pay close attention to ++letter. What this does is increment the memory address the pointer is looking at by the size of the type it is pointing to.
Let's break this down a bit more, re-read the above sentence a few times then continue on.
If I have a type that is sizeof(T) == 4, every ++myPointerValue will shift 4 spaces in memory to point to the next "value" of that type. This is part of why the pointer "type" matters.
char text[] { 'H', 'e', 'l', 'l', 'o', '\0' }; //could be char text[] = "Hello"; but I want to show the \0 explicitly
char* letter = text;
for (char* letter = &text[0]; *letter != '\0';++letter){
std::cout << "[" << *letter << "]";
}
std::cout << std::endl;
The above will loop over the string as long as there is no '\0' (null) character. Keep in mind this can be dangerous and is a common source of insecurity in programs. Assuming your array is terminated by some value, but then getting an array that overflows allowing you to read arbitrary memory. That's a high level description anyway.
For that reason it is much better to be explicit with string length and use safer methods such as std::string in regular use.
Alright, and as a final example to put things into context. Let's say I have several discreet "cells" that I want to link together into one coherent "list". The most natural implementation of this with non-contiguous memory is to use pointers to direct each node to the next one in the sequence.
With pointers you can create all sorts of complex data structures, trees, lists, and more!
struct Node {
int value = 0;
Node* previous = nullptr;
Node* next = nullptr;
};
struct List {
List(){
head = new Node();
tail = head;
}
~List(){
std::cout << "Destructor: " << std::endl;
Node* current = head;
while (current != nullptr){
Node* next = current->next;
std::cout << "Deleting: " << current->value << std::endl;
delete current;
current = next;
}
}
void Append(int value){
Node* previous = tail;
tail = new Node();
tail->value = value;
tail->previous = previous;
previous->next = tail;
}
void Print(){
std::cout << "Printing the List:" << std::endl;
Node* current = head;
for (Node* current = head; current != nullptr;current = current->next){
std::cout << current->value << std::endl;
}
}
Node* tail;
Node* head;
};
And putting it to use:
List sampleList;
sampleList.Append(5);
sampleList.Append(6);
sampleList.Append(7);
sampleList.Append(8);
sampleList.Print();
List may seem complicated at a glance, but I am not introducing any new concepts here. This is exactly the same things I covered above, just implemented with a purpose.
Homework for you to completely understand pointers would be to provide two methods in List:
Node* NodeForIndex(int index)
void InsertNodeAtIndex(int index, int value)
This list implementation is exceptionally poor. std::list is a much better example, but it most cases due to data locality you really want to stick with std::vector. Pointers are exceptionally powerful tools, and fundamental in computer science. You need to understand them to appreciate how the common data types you rely on every day are composed, and in time you will come to appreciate the explicit separation of value from pointer in C++.
Beyond simple pointers: std::shared_ptr
std::shared_ptr gives C++ the ability to deal with reference counted pointers. That is to say, it gives a similar behavior to Javascript object assignment (where an object is destroyed when the last reference to that object is set to null or destroyed).
std::shared_ptr is just like any other stack based variable. It ties its lifetime to the stack, and then holds a pointer to memory allocated on the heap. In this regard, it encapsulates the concept of a pointer in a safer manner than having to remember to delete.
Let's re-visit our earlier example that did leak memory:
{
new ScopeTest("a"); //Create a
} //Whoa, we haven't destroyed it! Now we are leaking memory!
With a shared_ptr we can do the following:
{
std::shared_ptr<ScopeTest> a(new ScopeTest("a")); //Create a
}//Destroy a
And, a little more complex:
{
std::shared_ptr<ScopeTest> showingSharedOwnership;
{
std::shared_ptr<ScopeTest> a(new ScopeTest("a")); //"Create a" (ref count 1)
showingSharedOwnership = a; //increments a's ref count by 1. (now 2)
} //the shared_ptr named a is destroyed, decrements ref count by 1. (now 1)
} //"Destroy a" showingSharedOwnership dies and decrements the ref count by 1. (now 0)
I won't go too much further here, but this should open your mind to pointers.

Related

c++ Occasional Dynamic Pointer Crashing

I have made a program to take in float inputs from a user to create a dynamic array (Then use those inputs with functions to find basic stuff like max,min,sum,avg but that stuff works fine so I don't think Ill include that here for the purpose of not creating a wall of code).
It works about half the time and while I have some theories about the cause I cant put my finger on a solution.
int main() {
int Counter = 0;
float *UsrIn = nullptr;
float Array[Counter];
My first thought was that the part below was the issue. My class hasn't really gone over what notation (I assume it refers to bytes so maybe scientific notation would work) to use with new that I can recall. I just tried 20 for the sake of testing and it seemed to work(probably a silly assumption in hindsight).
UsrIn = new float[(int)20];
cout << "Enter float numbers:" << endl;
cout << "Enter '9999999' to quit:" << endl;
cin >> *UsrIn; // User Input for pointer Dynamic Array
Array[Counter] = *UsrIn;
while(*UsrIn!=9999999) // User Input for Dynamic Array
{
Counter++;
UsrIn++;
cin >> *UsrIn;
Array[Counter] = *UsrIn;
}
delete UsrIn;
delete[] UsrIn;
My other thought was that maybe a pointer address was already in use by something else or maybe it was invalid somehow. I don't know of a way to test for that because the crash I occasionally get only happens when exiting the while loop after entering "9999999"
As a side note I'm not getting any warnings or error messages just a crashed program from eclipse.
Variable-length arrays are not universally supported in C++ implementations, although your compiler clearly supports them. The problem, from what you've described, is with this code:
int main() {
int Counter = 0;
float *UsrIn = nullptr;
float Array[Counter];
You're defining a variable-length array of size 0. So, although you're allocating 20 entries for UsrIn, you're not allocating any memory for Array. The intention of variable-length arrays is to allocate an array of a given size where the size is not actually known until run time. Based on your other code, that's not really the situation here. The easiest thing to do is just change the Array size to match your UsrIn size, e.g.:
float Array[20];
If you really want more of a dynamic behavior, you could use std::vector<float>
std::vector<float> Array;
...
Array.push_back(*UsrIn);

Multidimensional array allocation with Cuda Unified Memory on Power 8

I'm trying to allocate multi dimensional arrays by using CUDA UMA on Power 8 system. However, I'm having issue while size is getting bigger. The code I'm using is below. When size is 24 x 24 x 24 x 5 works fine. When I increase it to 64 x 64 x 64 x 8 I am having " out of memory" even though I have memory in my device. Afaik, I suppose to be able to allocate memory via UMA as much as GPU device physical memory. So I would not expect any error. Currently my main configuration is Power 8 and Tesla k40 where I am having seg fault during runtime. However, I tried the code piece I provided on x86 + k40 machine. It surprisingly worked.
BTW, if you tell me another way to do that apart from transforming all my code from 4d array to 1d array, I'll so appreciate.
Thanks in advance
Driver: Nvidia 361
#include <iostream>
#include <cuda_runtime.h>
void* operator new[] (size_t len) throw(std::bad_alloc) {
void *ptr;
cudaMallocManaged(&ptr, len);
return ptr;
}
template<typename T>
T**** create_4d(int a, int b, int c, int d){
T**** ary = new T***[a];
for(int i = 0; i < a; ++i)
{
ary[i] = new T**[b];
for(int j = 0; j < b; ++j){
ary[i][j] = new T*[c];
for(int k = 0; k < c; ++k){
ary[i][j][k] = new T[d];
}
}
}
return ary;
}
int main() {
double ****data;
std::cout << "allocating..." << std::endl;
data = create_4d<double>(32,65,65,5);
std::cout << "Hooreey !!!" << std::endl;
//segfault here
std::cout << "allocating..." << std::endl;
data = create_4d<double>(64,65,65,5);
std::cout << "Hooreey !!!" << std::endl;
return 0;
}
There's been a considerable amount of dialog on your cross-posting here including an answer to your main question. I'll use this answer to summarize what is there as well as to answer this question specifically:
BTW, if you tell me another way to do that apart from transforming all my code from 4d array to 1d array, I'll so appreciate.
One of your claims is that you are doing proper error checking (" I caught error propoerly."). You are not. CUDA runtime API calls (including cudaMallocManaged) by themselves do not generate C++ style exceptions, so your throw specification on the new operator definition is meaningless. CUDA runtime API calls return an error code. If you want to do proper error checking, you must collect this error code and process it. If you collect the error code, you can use it to generate an exception if you wish, and an example of how you might do that is contained in the canonical proper CUDA error checking question, as one of the answers by Jared Hoberock. As a result of this oversight, when your allocations eventually fail, you are ignoring this, and then when you attempt to use those (non-) allocated areas for subsequent pointer storage, you generate a seg fault.
The proximal reason for the allocation failure is that you are in fact running out of memory, as discussed in your cross-posting. You can confirm this easily enough with proper error checking. Managed allocations have a granularity, and so when you request allocations of relatively small amounts, you are in fact using more memory than you think - the small allocations you are requesting are each being rounded up to the allocation granularity. The size of the allocation granularity varies by system type, and so the OpenPower system you are operating on has a much larger allocation granularity than the x86 system you compared it to, and as a result you were not running out of memory on the x86 system, but you were on the Power system. As discussed in your cross-posting, this is easy to verify with strategic calls to cudaMemGetInfo.
From a performance perspective, this is a pretty bad approach to multidimensional allocations for several reasons:
The allocations you are creating are disjoint, connected by pointers. Therefore, to access an element by pointer dereferencing, it requires 3 or 4 such dereferences to go through a 4-subscripted pointer array. Each of these dereferences will involve a device memory access. Compared to using simulated 4-D access into a 1-D (flat) allocation, this will be noticeably slower. The arithmetic associated with converting the 4-D simulated access into a single linear index will be much faster than traversing through memory via pointer-chasing.
Since the allocations you are creating are disjoint, the managed memory subsystem cannot coalesce them into a single transfer, and therefore, under the hood, a number of transfers equal to the product of your first 3 dimensions will take place, at kernel launch time (and presumably at termination, ie. at the next cudaDeviceSynchronize() call). This data must all be transferred of course, but you will be doing a large number of very small transfers, compared to a single transfer for a "flat" allocation. The associated overhead of the large number of small transfers can be significant.
As we've seen, the allocation granularity can seriously impact the memory usage efficiency of such an allocation scheme. What should be only using a small percentage of system memory ends up using all of system memory.
Operations that work on contiguous data from "row" to "row" of such an allocation will fail, because the allocations are disjoint. For example, such a matrix or a subsection of such a matrix could not be reliably passed to a CUBLAS linear algebra routine, as the expectation for that matrix would have contiguity of row storage in memory associated with it.
The ideal solution would be to create a single flat allocation, and then use simulated 4-D indexing to create a single linear index. Such an approach would address all 4 concerns above. However it requires perhaps substantial code refactoring.
We can however come up with an alternate approach, which preserves the 4-subscripted indexing, but otherwise addresses the concerns in items 2, 3, and 4 above by creating a single underlying flat allocation.
What follows is a worked example. We will actually create 2 managed allocations: one underlying flat allocation for data storage, and one underlying flat allocation (regardless of dimensionality) for pointer storage. It would be possible to combine these two into a single allocation with some careful alignment work, but that is not required to achieve any of the proposed benefits.
The basic methodology is covered in various other CUDA questions here on the SO tag, but most of those have host-side usage (only) in view, since they did not have UM in view. However, UM allows us to extend the methodology to host- and device-side usage. We will start by creating a single "base" allocation of the necessary size to store the data. Then we will create an allocation for the pointer array, and we will then work through the pointer array, fixing up each pointer to point to the correct location in the pointer array, or else to the correct location in the "base" data array.
Here's a worked example, demonstrating host and device usage, and including proper error checking:
$ cat t1271.cu
#include <iostream>
#include <assert.h>
template<typename T>
T**** create_4d_flat(int a, int b, int c, int d){
T *base;
cudaError_t err = cudaMallocManaged(&base, a*b*c*d*sizeof(T));
assert(err == cudaSuccess);
T ****ary;
err = cudaMallocManaged(&ary, (a+a*b+a*b*c)*sizeof(T*));
assert(err == cudaSuccess);
for (int i = 0; i < a; i++){
ary[i] = (T ***)((ary + a) + i*b);
for (int j = 0; j < b; j++){
ary[i][j] = (T **)((ary + a + a*b) + i*b*c + j*c);
for (int k = 0; k < c; k++)
ary[i][j][k] = base + ((i*b+j)*c + k)*d;}}
return ary;
}
template<typename T>
void free_4d_flat(T**** ary){
if (ary[0][0][0]) cudaFree(ary[0][0][0]);
if (ary) cudaFree(ary);
}
template<typename T>
__global__ void fill(T**** data, int a, int b, int c, int d){
unsigned long long int val = 0;
for (int i = 0; i < a; i++)
for (int j = 0; j < b; j++)
for (int k = 0; k < c; k++)
for (int l = 0; l < d; l++)
data[i][j][k][l] = val++;
}
void report_gpu_mem()
{
size_t free, total;
cudaMemGetInfo(&free, &total);
std::cout << "Free = " << free << " Total = " << total <<std::endl;
}
int main() {
report_gpu_mem();
unsigned long long int ****data2;
std::cout << "allocating..." << std::endl;
data2 = create_4d_flat<unsigned long long int>(64, 63, 62, 5);
report_gpu_mem();
fill<<<1,1>>>(data2, 64, 63, 62, 5);
cudaError_t err = cudaDeviceSynchronize();
assert(err == cudaSuccess);
std::cout << "validating..." << std::endl;
for (int i = 0; i < 64*63*62*5; i++)
if (*(data2[0][0][0] + i) != i) {std::cout << "mismatch at " << i << " was " << *(data2[0][0][0] + i) << std::endl; return -1;}
free_4d_flat(data2);
return 0;
}
$ nvcc -arch=sm_35 -o t1271 t1271.cu
$ cuda-memcheck ./t1271
========= CUDA-MEMCHECK
Free = 5904859136 Total = 5975900160
allocating...
Free = 5892276224 Total = 5975900160
validating...
========= ERROR SUMMARY: 0 errors
$
Notes:
This still involves pointer chasing inefficiency. I don't know of a method to avoid that without removing the multiple subscript arrangement.
I've elected to use 2 different indexing schemes in host and device code. In device code, I am using a normal 4-subscripted index, to demonstrate the utility of that. In host code, I am using a "flat" index, to demonstrate that the underlying storage is contiguous and contiguously addressable.

Removing from a std::list with objects

I was taught always to use a pointer list when storing objects, but I started using lists with objects in them instead. So I'm wondering how do I properly remove an object from a list?
The first code example removes from a pointer list and works all right, but the second one gives an error when running. Do I need to use delete when working with list with objects?
using namespace std;
struct SomeObject{
SomeObject(int i){
something=i;
}
int something;
};
void main(){
list<SomeObject*> pointerList;
SomeObject * op = new SomeObject(2);
pointerList.push_back(op);
auto pit = pointerList.begin();
pointerList.erase(pit);
delete *pit;
cout<<(**pit).something<<endl;
list<SomeObject> objectList;
SomeObject o(1);
objectList.push_back(o);
auto oit = objectList.begin();
objectList.erase(oit);
delete &oit;//this one
cout<<oit->something<<endl;
int i;
cin >> i;
}
Also what are down and upsides with doing it this way?
You get the error because oit is an iterator, not a pointer. You use delete on pointers acquired with new. Iterators look like pointers, but they are not pointers. In the example you gave it's just wrong to use delete.
I think it would be more idiomatic (and correct!) this way:
list<SomeObject*> pointerList;
SomeObject * op = new SomeObject(2);
pointerList.push_back(op);
auto pit = pointerList.front();
pointerList.pop_front();
// delete *pit; // wrong
cout << (**pit).something << endl;
list<SomeObject> objectList;
SomeObject o(1);
objectList.push_back(o);
auto oit = objectList.front();
objectList.pop_front();
// delete &oit; // wrong
cout << oit->something << endl;

vector data check

hi a have a function that reads from a text file line by line each line I do some operations on it substitute a string..etc
then I push_back that line into a vector
this is my class in Parser.h
class Parser
{// start class
public:
vector<const char*> patterns;
Parser();
~Parser();
void RuleParser(const char *TextFileName); // this is the function that takes the file name
private:
};// end class
segment from function RuleParser
std::ifstream ifs(TextFileName);
while (!ifs.eof())
{
.
.modification code
.
patterns.push_back((buildString).c_str()); //buildString is the modified line
cout << buildString << endl;
}
but when I try to check out if the data in the vector is correct it output totally different data.
I even put a cout after the push_back to check it's integrty but I found buildString is correct... thats the data each time being pushed ... what I am doing wrong.
here is the loop I use to see if my data correct.
for (int i = 0;i < patterns.size() ;i++)
{
cout << patterns.at(i) << endl;
}
Well patterns is the collection of pointers so you end up push_back'ing a pointer to the same buildString in each iteration of the loop, instead of push_back'ing the string contents. Then when buildString changes in next iteration of the loop, the pointer becomes invalid but it still remains in patterns - not good
I suggest you declare patterns as:
vector<std::string> patterns;
This way when you do:
patterns.push_back(buildString.c_str())
the contents of the string will be copied instead of the pointer, and remain valid througout.

Acessing a struct member, using a pointer to a vector of structs. Error:base operand of '->' has non-pointer type

#include <iostream>
#include <vector>
using namespace std;
struct s_Astruct {
vector <int> z;
};
int main ()
{
vector <s_Astruct> v_a;
for(int q=0;q<10;q++)
{
v_a.push_back(s_Astruct());
for(int w =0;w<5;w++)
v_a[q].z.push_back(8);
}
vector <s_Astruct> * p_v_a = & v_a;
cout << p_v_a[0]->z[4]; //error: base operand of '->' has non-pointer type
//'__gnu_debug_def::vector<s_Astruct, std::allocator<s_Astruct> >'
}
There seems to be some issue with this sort of operation that I don't understand. In the code that I'm working on I actually have things like p_class->vector[]->vector[]->int; and I'm getting a similar error.
You want to do this:
cout << ((*p_v_a)[0]).z[4];
What you are doing is dereferencing the pointer by using [] and grabbing the 0'th offset, and then trying to dereference the non-pointer.
Another way to do it (which is just ugly):
cout << (p_v_a[0][0]).z[4];
p_v_a is a vector*, making p_v_a[0] a vector (since p_v_a[0] is equivalent to *(p_v_a+0)), so using the pointer to member operator (->) isn't going to work on that. You likely want (*p_v_a)[0].z[4].
When you use the index [] operator on the pointer, that also dereferences it. Using the infix dereference operator -> on the non-pointer type then results, correctly, in the error you describe.
In the following:
vector<s_Astruct>* p_v_a = &v_a;
cout << p_v_a[0]->z[4]
You have a pointer to a vector, but you didn't dereference that pointer before attempting to call operator[]. You then attempted to dereference the s_Astruct at index 0, but that is not a pointer.
Try this:
vector<s_Astruct>* p_v_a = &v_a;
cout << (*p_v_a)[0].z[4];
Hope that helps.
This was driving me buggo- I'd managed to get
std::cout << (nsNLs->back()).name
working, but I couldn't get the index array reference to work, (even with parens I didn't need).
std::cout << ||here?|| nsNLs ||here?|| [ intVal ] ||here?|| name
I tried every variation of dereferenceing and parenthesizing around the pointer to the vector, without hitting on ( ||thing pointed to by|| passedVariable )[ ].name
"." works because at the end of the two stage dereference, we're looking at an instance of the struct, not anything pointed to something, just a concrete chunk of memory.
#Mark, very clear explanation, you lead with something that works, and the operation is unusual enough that I feel better with the parens around the vector object dereference AND the array element / pointer dereference. I saw your solution, tried it, and it worked.
#Tomalek, Your answer is second easiest to follow and gets an extra point in my book for showing the problem, going through it step by step, explaining the error, and then suggesting the fix. Slightly sportier than Mark, only one set of parentheses.
#user470379, your answer is correct and you show a successful solution, but its bit harder to follow and the answer is at the end.
Thank you all three, I voted you up.

Resources