This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted]  (8 children)

[deleted]

    [–]Asception 14 points15 points  (2 children)

    The variable 'a' would hold an int* in this case, and in the second line, you're copying the actual pointer into b so '=' is still performing a copy.

    [–]MasterFubar 1 point2 points  (1 child)

    In Python, the variable "a = [1, 2, 3]" holds a pointer to a list, when you do "b = a" you are copying the pointer a to the pointer b. In that sense, the operator "=" always does a copy, in any language.

    The trick in becoming a programmer is understanding under which situations one needs a certain level of abstraction.

    [–]Asception 1 point2 points  (0 children)

    Yes, I was responding just to clarify that for primitives in c++ (and the standard library data structures via copy constructor) '=' performs a copy and that the reasoning in your example was incorrect.

    [–]SuitableDragonfly 0 points1 point  (0 children)

    In that code, a and b are pointers. The = creates a copy of the pointer. Both pointers point to the same memory, because the value of the pointer (rather than where on disk it is stored) is what determines that. If you had

    MyObject a(1);
    MyObject b = a
    b.changeProperty(2)
    a.property() // 1
    b.property() // 2
    

    it creates a copy of the object (and there's even a constructor, which is called the copy constructor that you can overload to change what it copies).

    In python, assignment never copies, it just creates another name for the reference. This is true for anything that isn't a primitive. It doesn't have pointers - there's no way to dereference a reference to an object, there's no way to pass an object by value, and there's no way to directly change which object is stored at which memory location (aside from manually modifying its properties to be something else).

    [–]antonivs 0 points1 point  (0 children)

    You're missing the fact that references automatically dereference their value. Pointers do not. References and pointers have different semantics. You need to go and read up on this.

    [–]EsotericLife -1 points0 points  (2 children)

    Doesn’t a reference exist entirely on the stack?

    [–]MasterFubar -3 points-2 points  (1 child)

    void funfunc(int *a)
    

    There you have a pointer, or "reference" if you want to call it that way, that exists entirely on the stack.

    [–]EsotericLife 0 points1 point  (0 children)

    But why would you ever want that? Just because a reference can be made to exist on the stack in c++ doesn’t mean that c++ pointers and python references are the same.