Xem Nhiều 2/2023 #️ What Are The Differences Between A Pointer Variable And A Reference Variable In C++? # Top 10 Trend | Sansangdethanhcong.com

Xem Nhiều 2/2023 # What Are The Differences Between A Pointer Variable And A Reference Variable In C++? # Top 10 Trend

Cập nhật thông tin chi tiết về What Are The Differences Between A Pointer Variable And A Reference Variable In C++? mới nhất trên website Sansangdethanhcong.com. Hy vọng nội dung bài viết sẽ đáp ứng được nhu cầu của bạn, chúng tôi sẽ thường xuyên cập nhật mới nội dung để bạn nhận được thông tin nhanh chóng và chính xác nhất.

The direct answer

What is a reference in C++? Some specific instance of type that is not an object type.

What is a pointer in C++? Some specific instance of type that is an object type.

From the ISO C++ definition of object type:

An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not cv void.

It may be important to know, object type is a top-level category of the type universe in C++. Reference is also a top-level category. But pointer is not.

Pointers and references are mentioned together in the context of compound type. This is basically due to the nature of the declarator syntax inherited from (and extended) C, which has no references. (Besides, there are more than one kind of declarator of references since C++ 11, while pointers are still “unityped”: &+&& vs. *.) So drafting a language specific by “extension” with similar style of C in this context is somewhat reasonable. (I will still argue that the syntax of declarators wastes the syntactic expressiveness a lot, makes both human users and implementations frustrating. Thus, all of them are not qualified to be built-in in a new language design. This is a totally different topic about PL design, though.)

Otherwise, it is insignificant that pointers can be qualified as a specific sorts of types with references together. They simply share too few common properties besides the syntax similarity, so there is no need to put them together in most cases.

Note the statements above only mentions “pointers” and “references” as types. There are some interested questions about their instances (like variables). There also come too many misconceptions.

The differences of the top-level categories can already reveal many concrete differences not tied to pointers directly:

Object types can have top-level cv qualifiers. References cannot.

Variable of object types do occupy storage as per the abstract machine semantics. Reference do not necessary occupy storage (see the section about misconceptions below for details).

A few more special rules on references:

Compound declarators are more restrictive on references.

References can collapse.

Special rules on && parameters (as the “forwarding references”) based on reference collapsing during template parameter deduction allow “perfect forwarding” of parameters.

References have special rules in initialization. The lifetime of variable declared as a reference type can be different to ordinary objects via extension.

BTW, a few other contexts like initialization involving std::initializer_list follows some similar rules of reference lifetime extension. It is another can of worms.

The misconceptions

I know references are syntactic sugar, so code is easier to read and write.

Technically, this is plain wrong. References are not syntactic sugar of any other features in C++, because they cannot be exactly replaced by other features without any semantic differences.

(Similarly, lambda-expressions are not syntactic sugar of any other features in C++ because it cannot be precisely simulated with “unspecified” properties like the declaration order of the captured variables, which may be important because the initialization order of such variables can be significant.)

C++ only has a few kinds of syntactic sugars in this strict sense. One instance is (inherited from C) the built-in (non-overloaded) operator [], which is defined exactly having same semantic properties of specific forms of combination over built-in operator unary * and binary +.

Storage

So, a pointer and a reference both use the same amount of memory.

The statement above is simply wrong. To avoid such misconceptions, look at the ISO C++ rules instead:

From [intro.object]/1:

… An object occupies a region of storage in its period of construction, throughout its lifetime, and in its period of destruction. …

From [dcl.ref]/4:

It is unspecified whether or not a reference requires storage.

Note these are semantic properties.

Pragmatics

Even that pointers are not qualified enough to be put together with references in the sense of the language design, there are still some arguments making it debatable to make choice between them in some other contexts, for example, when making choices on parameter types.

But this is not the whole story. I mean, there are more things than pointers vs references you have to consider.

If you don’t have to stick on such over-specific choices, in most cases the answer is short: you do not have the necessity to use pointers, so you don’t. Pointers are usually bad enough because they imply too many things you don’t expect and they will rely on too many implicit assumptions undermining the maintainability and (even) portability of the code. Unnecessarily relying on pointers is definitely a bad style and it should be avoided in the sense of modern C++. Reconsider your purpose and you will finally find that pointer is the feature of last sorts in most cases.

Sometimes the language rules explicitly require specific types to be used. If you want to use these features, obey the rules.

Copy constructors require specific types of cv-& reference type as the 1st parameter type. (And usually it should be const qualified.)

Move constructors require specific types of cv-&& reference type as the 1st parameter type. (And usually there should be no qualifiers.)

Overloaded operator= as special member functions requires reference types similar to 1st parameter of copy/move constructors.

Postfix ++ requires dummy int.

If you know pass-by-value (i.e. using non-reference types) is sufficient, use it directly, particularly when using an implementation supporting C++17 mandated copy elision. (Warning: However, to exhaustively reason about the necessity can be very complicated.)

If you want to operate some handles with ownership, use smart pointers like unique_ptr and shared_ptr (or even with homebrew ones by yourself if you require them to be opaque), rather than raw pointers.

If you are doing some iterations over a range, use iterators (or some ranges which are not provided by the standard library yet), rather than raw pointers unless you are convinced raw pointers will do better (e.g. for less header dependencies) in very specific cases.

If you know pass-by-value is sufficient and you want some explicit nullable semantics, use wrapper like std::optional, rather than raw pointers.

If you know pass-by-value is not ideal for the reasons above, and you don’t want nullable semantics, use {lvalue, rvalue, forwarding}-references.

Even when you do want semantics like traditional pointer, there are often something more appropriate, like observer_ptr in Library Fundamental TS.

The only exceptions cannot be worked around in the current language:

When you are implementing smart pointers above, you may have to deal with raw pointers.

Specific language-interoperation routines require pointers, like operator new. (However, cv-void* is still quite different and safer compared to the ordinary object pointers because it rules out unexpected pointer arithmetics unless you are relying on some non conforming extension on void* like GNU’s.)

Function pointers can be converted from lambda expressions without captures, while function references cannot. You have to use function pointers in non-generic code for such cases, even you deliberately do not want nullable values.

So, in practice, the answer is so obvious: when in doubt, avoid pointers. You have to use pointers only when there are very explicit reasons that nothing else is more appropriate. Except a few exceptional cases mentioned above, such choices are almost always not purely C++-specific (but likely to be language-implementation-specific). Such instances can be:

You have to serve to old-style (C) APIs.

You have to meet the ABI requirements of specific C++ implementations.

You have to interoperate at runtime with different language implementations (including various assemblies, language runtime and FFI of some high-level client languages) based on assumptions of specific implementations.

You have to improve efficiency of the translation (compilation & linking) in some extreme cases.

You have to avoid symbol bloat in some extreme cases.

Language neutrality caveats

If you come to see the question via some Google search result (not specific to C++), this is very likely to be the wrong place.

References in C++ is quite “odd”, as it is essentially not first-class: they will be treated as the objects or the functions being referred to so they have no chance to support some first-class operations like being the left operand of the member access operator independently to the type of the referred object. Other languages may or may not have similar restrictions on their references.

References in C++ will likely not preserve the meaning across different languages. For example, references in general do not imply nonnull properties on values like they in C++, so such assumptions may not work in some other languages (and you will find counterexamples quite easily, e.g. Java, C#, …).

There can still be some common properties among references in different programming languages in general, but let’s leave it for some other questions in SO.

(A side note: the question may be significant earlier than any “C-like” languages are involved, like ALGOL 68 vs. PL/I.)

What’S The Difference Between Which And Where?

What’s the difference between which and where?

such like these examples:

The building which I visited was 350 m tall.

The restaurant where my cousin works is really expensive.

My friend is taking me to a shopping centre which is huge.

This hotel where we spent our summer holiday last year.

The relative pronouns “which” and “where” specifically describe a place. “Where” is followed by a noun or pronoun.

That’s a great question as many students are confused by the way they are used in some sentences. The difference, however, is not too difficult to understand.

Which, is a pronoun and determiner.

Let’s use your sentences to answer the question and provide more details.

This sentence correctly applies the determiner “which,” to provide further information the building had already been mentioned earlier in the sentence.

Which, can be used both before and after as a pronoun and determiner. Here are some further examples.

coffee would you like, the cappuccino or expresso?

The cappuccino has milk, but the expresso doesn’t, one do you want?

A cappuccino is not as strong as an expresso has no milk.

The in this sentence is to not referring to the place but the situation of the cousin, because it was used after the place had already been mentioned. To prove this point, if we removed this part of the clause, the sentence still makes sense – The restaurant is really expensive.

However, if we reword the sentence and use which as a determiner, the focus of the sentence returns to the place/restaurant as we are also using ‘at’ as a preposition of place.

My friend is taking me to a shopping center which is huge.

Again in this sentence is used as a determiner to provide further information about the shopping center mentioned beforehand. It helps us understand that is is the shopping center which is huge and not the friend! (That could be embarrassing!)

This hotel where we spent our summer holiday last year.

Technically this sentence should read, ‘this IS THE hotel where we spent our summer last year.’ Again the use of in this sentence is to the situation, not the hotel, as it comes after the place has already been mentioned. To prove the point we could eliminate the word entirely and use the preposition ‘at’ instead.

This is the hotel we spent our summer last year.

To use for the place itself, place the word before the noun.

We can meet where the hotel is, the one that we spent summer at last year.

Just remember, which and where are not interchangeable alone, if swapped other parts of the sentence would need to be corrected as well. When changed they can modify the focus or meaning of the clause.

Put simply.

If you are focusing on a situation or place use .

If you are making a distinction between two or more things, then use .

What’S The Difference Between Costs And Expenses?

Business people use two terms – “cost” and “expense” – every day. But what do these two terms mean? Are they just different words for the same concept?

We use the two terms interchangeably in our business conversations, but they have different meanings and applications in business. We’ll look at cost and expense -in general, and then as they apply to business accounting and taxes.

Costs and Expenses Compared

First, a general definition of both terms:

Cost is “an amount that has to be paid or spent to buy or obtain something.” Cost can be specific, like, “What’s the cost of that car?” or it can be a penalty, like “Consider the cost of missing that event.”

Notice also that cost implies a one-time event, like a purchase. The term “cost” is often used in business in the context of marketing and pricing strategies, while the term “expense” implies something more formal and something related to the business balance sheet and taxes.

The definition of expense sounds similar to that of cost: “an amount of money that must be spent especially regularly to pay for something.” But notice the words “especially regularly.”

For example:

the cost of a product is often linked to the price to the producer or seller.

Expenses show up on your business profit and loss statement.

An expense is an ongoing payment, like utilities, rent, payroll, and marketing. For example, the expense of rent is needed to have a location to sell from, to produce revenue.

You can also consider an expense as money you spend to generate revenue.

You need to spend money on rent and utilities if you want to have a retail store

You need to spend money on a web page to get customers over the internet

Costs vs. Expenses in Accounting

Accounting types use the term “cost” to describe several different instances in business situations.

Fixed and Variable Costs. Cost accountants spend there time looking at costs associated with making a product or providing services, to prepare budgets and analyze profits.

Cost of goods sold. The term cost of goods sold r efers to the calculation done at the end of an accounting year for businesses that sell products. The cost of goods sold includes several different types of costs:

Direct costs to make and ship products:

Products bought for resale

Raw materials to make products

Packaging and shipping products to customers

Inventory of finished products

Direct overhead costs for utilities and rent for a warehouse or factory

Indirect costs like labor, storage costs, and pay of supervisors for the factory or warehouse.

Cost in Accounting

Accountants use cost to refer specifically to business assets, and even more specifically to assets that are depreciated (called depreciable assets). The cost (sometimes called cost basis) of an asset includes every cost to buy, deliver, and set up the asset, and to train employees in its use.

For example, if a manufacturing business buys a machine, the cost includes shipping, set-up, and training. Cost basis is used to establish the basis for depreciation and other tax factors.

The cost of assets shows up on the business accounting on the balance sheet. The original cost will always be shown, then accumulated depreciation will be subtracted, with the result as book value of that asset. All the business assets are combined for the purpose of the balance sheet.

Expenses in Accounting

Expenses in accounting are used to determine profit. The calculation for profit is: Income minus Expenses Equals Profit. Accountants look at two kinds of expenses: fixed and variable.

Fixed expenses must be paid every month even if there are no sales.

Variable expenses change with the level of sales.

Cost vs. Expenses and Taxes

Expenses are used to produce revenue and they are deductible on your business tax return, reducing the business’s income tax bill. To be deductible, they must be “ordinary and necessary” to the business. 

Costs don’t directly affect taxes, but the cost of an asset is used to determine the depreciation expense for each year, which is a deductible business expense. Depreciation is considered a “non-cash expense” because no one writes a check for depreciation, but the business can use it to reduce income for tax purposes.

The Bottom Line on Costs vs. Expenses

What Is The Difference Between Departure And Leave?

As nouns the difference between departure and leave

is that departure is the act of departing or something that has departed while leave is (cricket) the action of the batsman not attempting to play at the ball or leave can be permission to be absent; time away from one’s work.

As a verb leave is

to cause or allow (something) to remain as available; to refrain from taking (something) away; to stop short of consuming or otherwise depleting (something) entirely or leave can be to give leave to; allow; permit; let; grant or leave can be (rare) to produce leaves or foliageoxford english dictionary , 2nd ed.

Noun

()

The act of departing or something that has departed.

* {{quote-book, year=1922, author=(Ben Travers), title=(A Cuckoo in the Nest)

, chapter=5 citation , passage=The departure was not unduly prolonged. In the road Mr. Love and the driver favoured the company with a brief chanty running: “Got it?-No, I ain’t, ‘old on,-Got it? Got it?-No, ‘old on sir.”}}

* {{quote-news, year=2011, date=April 10, author=Alistair Magowan, work=BBC Sport

, title= Aston Villa 1-0 Newcastle , passage=Villa spent most of the second period probing from wide areas and had a succession of corners but despite their profligacy they will be glad to overturn the 6-0 hammering they suffered at St James’ Park in August following former boss Martin O’Neill’s departure .}}

A deviation from a plan or procedure.

* Prescott

(euphemism) A death.

* Bible, 2 Tim. iv. 6

* Sir Philip Sidney

(navigation) The distance due east or west made by a ship in its course reckoned in plane sailing as the product of the distance sailed and the sine of the angle made by the course with the meridian.

(legal) The desertion by a party to any pleading of the ground taken by him in his last antecedent pleading, and the adoption of another.

(obsolete) Division; separation; putting away.

* Milton

Etymology 1

From ( etyl) leven, from ( etyl) (whence Danish levne). More at .

Verb

To have a consequence or remnant.

#To cause or allow (something) to remain as available; to refrain from taking (something) away; to stop short of consuming or otherwise depleting (something) entirely.

#:

#*, chapter=7

, title= The Mirror and the Lamp , passage=[…] St.?Bede’s at this period of its history was perhaps the poorest and most miserable parish in the East End of London. Close-packed, crushed by the buttressed height of the railway viaduct, rendered airless by huge walls of factories, it at once banished lively interest from a stranger’s mind and left only a dull oppression of the spirit.}}

#*{{quote-magazine, year=2013, month=May-June, author= David Van Tassel], [http://www.americanscientist.org/authors/detail/lee-dehaan Lee DeHaan

, title= Wild Plants to the Rescue , volume=101, issue=3, magazine=( American Scientist) , passage=Plant breeding is always a numbers game.

#To cause, to result in.

#:

#*{{quote-book, year=1899, author=(Stephen Crane)

, title=, chapter=1 , passage=There was some laughter, and Roddle was left free to expand his ideas on the periodic visits of cowboys to the town. “Mason Rickets, he had ten big punkins a-sittin’ in front of his store, an’ them fellers from the Upside-down-F ranch shot ’em up

#*, chapter=23

, title= The Mirror and the Lamp , passage=The slightest effort made the patient cough. He would stand leaning on a stick and holding a hand to his side, and when the paroxysm had passed it left him shaking.}}

#*{{quote-magazine, date=2013-07-20, volume=408, issue=8845, magazine=(The Economist)

, title= Out of the gloom , passage=[Rural solar plant] schemes are of little help to industry or other heavy users of electricity. Nor is solar power yet as cheap as the grid. For all that, the rapid arrival of electric light to Indian villages is long overdue. When the national grid suffers its next huge outage, as it did in July 2012 when hundreds of millions were left in the dark, look for specks of light in the villages.}}

#(lb) To put; to place; to deposit; to deliver, with a sense of withdrawing oneself.

#:

#*Bible, (w) v. 24

#*:Leave there thy gift before the altar and go thy way.

#*(William Shakespeare) (1564-1616)

#*:The foot / That leaves the print of blood where’er it walks.

(lb) To depart; to separate from.

#To let be or do without interference.

#:

#(lb) To depart from; to end one’s connection or affiliation with.

#:

#*

, title=( The Celebrity), chapter=1 , passage=I was about to say that I had known the Celebrity from the time he wore kilts. But I see I will have to amend that, because he was not a celebrity then, nor, indeed, did he achieve fame until some time after I left New York for the West.}}

#(lb) To end one’s membership in (a group); to terminate one’s affiliation with (an organization); to stop participating in (a project).

#:

#(lb) To depart; to go away from a certain place or state.

#:

(lb) To transfer something.

#(lb) To transfer possession of after death.

#:

#(lb) To give (something) to someone; to deliver (something) to a repository; to deposit.

#:

#(lb) To transfer responsibility or attention of (something) (to someone); to stop being concerned with.

#:

To remain (behind); to stay.

*:

*:And whanne sire launcelot sawe them fare soo / he gat a spere in his hand / and there encountred with hym al attones syr bors sir Ector and sire Lyonel / and alle they thre smote hym atte ones with their speres

*

*:Carried somehow, somewhither, for some reason, on these surging floods, were these travelers,. Even such a boat as the Mount Vernon offered a total deck space so cramped as to leave secrecy or privacy well out of the question, even had the motley and democratic assemblage of passengers been disposed to accord either.

To stop, desist from; to “leave off” (+ noun / gerund).

*:When he had leeft speakynge, he sayde vnto Simon: Cary vs into the depe, and lett slippe thy nette to make a draught.

*(Alexander Pope) (1688-1744)

*:Now leave complaining and begin your tea.

Derived terms

* beleave * forleave * leave behind * leave for dead * leave no stone unturned * leave nothing in the tank * leave someone hanging * leave someone high and dry * leave someone holding the bag * leave off * leave out * leave in the lurch * leave well enough alone * not leave one’s thought * overleave * up and leave

Noun

()

(cricket) The action of the batsman not attempting to play at the ball.

(billiards) The arrangement of balls in play that remains after a shot is made (which determines whether the next shooter – who may be either the same player, or an opponent – has good options, or only poor ones).

* 1890 February 27, “Slosson’s Close Shave”], in [[w:New York Times, The New York Times] :

Etymology 2

From ( etyl) leve, from ( etyl) . Related to ( etyl) verlof, ( etyl) Erlaubnis. See also ( l).

Noun

(–)

Permission to be absent; time away from one’s work.

I’ve been given three weeks’ leave by my boss.

(senseid)(dated, or, legal) Permission.

The applicant now seeks leave to appeal and, if leave be granted, to appeal against these sentences.

(dated) Farewell, departure.

I took my leave of the gentleman without a backward glance.

Derived terms

* administrative leave * annual leave * by your leave * compassionate leave * leave of absence * maternity leave * on leave * parental leave * paternity leave * shore leave * sick leave * take French leave * take leave * ticket-of-leave

Verb

To give leave to; allow; permit; let; grant.

Verb

(rare) To produce leaves or foliage.Oxford English Dictionary , 2nd ed.

* 1868 , , The Rubáiyát of Omar Khayyám , 2nd edition:

Each Morn a thousand Roses brings, you say:

Bạn đang xem bài viết What Are The Differences Between A Pointer Variable And A Reference Variable In C++? trên website Sansangdethanhcong.com. Hy vọng những thông tin mà chúng tôi đã chia sẻ là hữu ích với bạn. Nếu nội dung hay, ý nghĩa bạn hãy chia sẻ với bạn bè của mình và luôn theo dõi, ủng hộ chúng tôi để cập nhật những thông tin mới nhất. Chúc bạn một ngày tốt lành!