Domanda

Quite recently, I ran across an old (but still funny) "If Programming Languages Were Essays" comic. I'm quite familiar with the majority of the languages on it, but I was a little confused about the one on C++.

Having just started C++ recently, I wasn't entirely sure why C++ is known for making tonnes of copies of objects. I went to do a little research, and found that when arguments are passed by value, a copy of the object is passed. However, plenty of languages do passing by value as a default so I don't think I'm hitting the right reason. As well, I got into copy constructors and how C++ has (unlike Java) a default copy constructor that does shallow copies, but that doesn't have me convinced either.

Can anybody shed some light on this conception of C++?

È stato utile?

Soluzione 2

Pass by value is not a problem for languages which default to making everything a reference.

But in C++, parameters default to value types unless you explicitly specify that they are taken by reference.

Furthermore, full copies happen on every assignment unless the assignment operator is overwritten to do something else.

class  Foo {
    int a;
    double d;
    uint64_t z;
}

Foo foo; 
Foo bar = foo; // just made a copy of all of the guts of Foo.

In Java, that would have been assigning a reference.

Altri suggerimenti

Pass by value and return by value is something C++ inherited from C. It was simple because data types in C (structs) were essentially packs of data. With some hacking with function pointers you can get "member functions", but it's not really the same as structs in C++.

However, as of the new standard, move semantics enables "moves" rather than copies. Moving an object from one place to another involves casting it down to an rvalue reference using std::move, and then passing it to either a move constructor or a move assignment operator that takes in an rvalue reference.

However, moving an object from one place to the other leaves it's "original" state in a valid but unknown state. For example, moving std::string objects from one place to another (i.e to another variable) yields the "original" to be the empty string.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top