• Sign In / Suggest an Article

Current ISO C++ status

Upcoming ISO C++ meetings

Upcoming C++ conferences

Compiler conformance status

ISO C++ committee meeting

March 18-23, Tokyo, Japan

April 17-20, Bristol, UK

using std::cpp 2024

April 24-26, Leganes, Spain  

C++ Now 2024

May 7-12, Aspen, CO, USA

June 24-29, St. Louis, MO, USA

July 2-5, Folkestone, Kent, UK

assignment operators

Assignment operators, what is “self assignment”.

Self assignment is when someone assigns an object to itself. For example,

Obviously no one ever explicitly does a self assignment like the above, but since more than one pointer or reference can point to the same object (aliasing), it is possible to have self assignment without knowing it:

This is only valid for copy assignment. Self-assignment is not valid for move assignment.

Why should I worry about “self assignment”?

If you don’t worry about self assignment , you’ll expose your users to some very subtle bugs that have very subtle and often disastrous symptoms. For example, the following class will cause a complete disaster in the case of self-assignment:

If someone assigns a Fred object to itself, line #1 deletes both this->p_ and f.p_ since *this and f are the same object. But line #2 uses *f.p_ , which is no longer a valid object. This will likely cause a major disaster.

The bottom line is that you the author of class Fred are responsible to make sure self-assignment on a Fred object is innocuous . Do not assume that users won’t ever do that to your objects. It is your fault if your object crashes when it gets a self-assignment.

Aside: the above Fred::operator= (const Fred&) has a second problem: If an exception is thrown while evaluating new Wilma(*f.p_) (e.g., an out-of-memory exception or an exception in Wilma ’s copy constructor ), this->p_ will be a dangling pointer — it will point to memory that is no longer valid. This can be solved by allocating the new objects before deleting the old objects.

Okay, okay, already; I’ll handle self-assignment. How do I do it?

You should worry about self assignment every time you create a class . This does not mean that you need to add extra code to all your classes: as long as your objects gracefully handle self assignment, it doesn’t matter whether you had to add extra code or not.

We will illustrate the two cases using the assignment operator in the previous FAQ :

If self-assignment can be handled without any extra code, don’t add any extra code. But do add a comment so others will know that your assignment operator gracefully handles self-assignment:

Example 1a:

Example 1b:

If you need to add extra code to your assignment operator, here’s a simple and effective technique:

Or equivalently:

By the way: the goal is not to make self-assignment fast. If you don’t need to explicitly test for self-assignment, for example, if your code works correctly (even if slowly) in the case of self-assignment, then do not put an if test in your assignment operator just to make the self-assignment case fast. The reason is simple: self-assignment is almost always rare, so it merely needs to be correct - it does not need to be efficient. Adding the unnecessary if statement would make a rare case faster by adding an extra conditional-branch to the normal case, punishing the many to benefit the few.

In this case, however, you should add a comment at the top of your assignment operator indicating that the rest of the code makes self-assignment is benign, and that is why you didn’t explicitly test for it. That way future maintainers will know to make sure self-assignment stays benign, or if not, they will need to add the if test.

I’m creating a derived class; should my assignment operators call my base class’s assignment operators?

Yes (if you need to define assignment operators in the first place).

If you define your own assignment operators, the compiler will not automatically call your base class’s assignment operators for you. Unless your base class’s assignment operators themselves are broken, you should call them explicitly from your derived class’s assignment operators (again, assuming you create them in the first place).

However if you do not create your own assignment operators, the ones that the compiler create for you will automatically call your base class’s assignment operators.

Please Login to submit a recommendation.

If you don’t have an account, you can register for free.

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
  • Solve Coding Problems
  • Placement new operator in C++
  • User Defined Literals in C++
  • C++ 17 | New ways to Assign values to Variables
  • Lambda expression in C++
  • How to print dimensions of multidimensional array in C++
  • std::any Class in C++
  • Using class to implement Vector Quantities in C++
  • Undefined Behavior in C and C++
  • Foreach in C++ and Java
  • static_cast in C++
  • reinterpret_cast in C++ | Type Casting operators
  • Generalized Lambda Expressions in C++14
  • Preventing Object Copy in C++ (3 Different Ways)
  • Advanced C++ with Boost Library
  • random header in C++ | Set 3 (Distributions)
  • "Access is Denied error" in C++ Visual Studio and How to resolve it
  • Trivial classes in C++
  • Scope resolution operator in C++
  • C++ program to find Machine Epsilon

Copy-and-Swap Idiom in C++

Before going into deep let us first have a look on the normal ‘overloaded assignment operator’ that we use.

The above assignment operator does the following things:

1. Self assignment check. 2. If there assignment is not to self, then it does following.     a) Deallocating memory assigned to this->ptr.     b) Allocating new memory to this->ptr and copying the values.     c) Returning *this.

Drawbacks of above approach:

  • The self assignment check: Self allocation is done very rarely so the self assignment check is not relevant in most of the scenarios. This just slows down the code.
  • Memory deallocation and allocation: As it can be seen that first the memory is deallocated (leaving the pointer dangling) and then the new chunk of memory is allocated. Now if due to some reason the memory is not allocated and an exception is thrown than the ‘this->ptr’ will be left dangling pointing to a deallocated memory. The scenario should be either the assignment is successful or the object should not be altered at all.

Here comes the role of copy-and-swap approach. This approach elegantly solves the above issue and also provides a scope for code re-usability. Lets see what exactly is it.

Consider the following code:

In the above example, the parameter to the ‘operator=()’ is passed by value which calls copy constructor to create a anyArrayClass object local to the ‘operator=()’. Than the value of the temp object is swapped with ‘*this’ object (LHS of assignment operator call).

Advantages:

  • No more self assignment check needed as the parameter is passed by value (This means no more memory deallocation is needed). Moreover as self allocation is very rare so the overhead of copying in case of self assignment should not be a problem.
  • Now as copy constructor is used to create the temp object therefore, the swapping will only be done if the temp object is at all created. Basically what we were doing manually there, the compiler is doing it for us in here.
  • Code re-useability: as we can see the ‘operator=()’ does not have much code in its body rather, we are using the copy constructor and swap function to do the job.

Please Login to comment...

  • cpp-advanced
  • 10 Best Zoho Vault Alternatives in 2024 (Free)
  • 10 Best Twitch Alternatives in 2024 (Free)
  • Top 10 Best Cartoons of All Time
  • 10 Best AI Instagram Post Generator in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Extra Clang Tools 19.0.0git documentation

Clang-tidy - bugprone-unhandled-self-assignment.

«   bugprone-unhandled-exception-at-new   ::   Contents   ::   bugprone-unique-ptr-array-mismatch   »

bugprone-unhandled-self-assignment ¶

cert-oop54-cpp redirects here as an alias for this check. For the CERT alias, the WarnOnlyIfThisHasSuspiciousField option is set to false .

Finds user-defined copy assignment operators which do not protect the code against self-assignment either by checking self-assignment explicitly or using the copy-and-swap or the copy-and-move method.

By default, this check searches only those classes which have any pointer or C array field to avoid false positives. In case of a pointer or a C array, it’s likely that self-copy assignment breaks the object if the copy assignment operator was not written with care.

See also: OOP54-CPP. Gracefully handle self-copy assignment

A copy assignment operator must prevent that self-copy assignment ruins the object state. A typical use case is when the class has a pointer field and the copy assignment operator first releases the pointed object and then tries to assign it:

There are two common C++ patterns to avoid this problem. The first is the self-assignment check:

The second one is the copy-and-swap method when we create a temporary copy (using the copy constructor) and then swap this temporary object with this :

There is a third pattern which is less common. Let’s call it the copy-and-move method when we create a temporary copy (using the copy constructor) and then move this temporary object into this (needs a move assignment operator):

When true , the check will warn only if the container class of the copy assignment operator has any suspicious fields (pointer or C array). This option is set to true by default.

CS253: Software Development with C++

Spring 2022, self-assignment.

Colorado State University logo

Show Lecture.Self-assignment as a slide show.

CS253 Self-assignment

check self assignment c

This illustrates the danger of self-assignment.

That is, when an object containing pointers or other handles to external resources is assigned to itself, you’ve got to be careful in operator= , or you might destroy your data before you copy it to yourself.

Copy Constructor General Outline

When a class contains a handle to external data, the copy constructor generally follows this pattern:

  • Copy the resource from the other object to this object.

That is, don’t just copy the handle (pointer, file descriptor, etc.). Instead you have to make an actual copy of the resource (copy the memory from new , create a new temporary file and copy the contents, etc.).

Of course, this is a copy constructor, not an assignment operator, so there was no previous value. We are constructing .

Assignment Operator General Outline

When a class contains a handle to external data, the assignment operator ( operator= ) generally follows this pattern:

  • Get rid of the old external data ( delete memory, close network socket, delete temporary file, unlock semaphore, etc.).
  • This is a silly class that stores a float in dynamic memory.
  • It works—so far.

Try Copy Constructor

  • That failed because the default copy ctor just copied the pointer.
  • Both objects’ dtors tried to free the same pointer … boom!
  • We deserve that, because we didn’t follow the general outline for a copy constructor. We got the default copy ctor.

Fixed Copy Constructor

  • The new copy ctor allocated more space and copied the data, not just the pointer.

Try Assignment Operator

  • The default assignment operator has the same problem.
  • Also, relying upon the compiler-created operator= when you've written the copy ctor is deprecated.

Fix Assignment Operator

  • The assignment operator now allocates space & copies the data.
  • Whaaaaaaaaaat?

Explanation

What happens inside a = a ?

  • First, delete the old data.
  • Second, copy the new data (that we just freed).
  • We must copy the data, but, sometimes, we can’t  !
  • If this is self-assignment, don’t do anything.
  • How to detect that?
  • See if the address of the left-hand-side ( this ) equals the address of the right-hand-side ( &rhs ).
  • The & in the declaration const HeapFloat &rhs means “reference to”, whereas the & in the expression   this != &rhs means ”address of”.

This Sounds Silly

  • Yeah, but, … so what? Nobody will ever really do that.
  • Not explicitly, no. But it might happen indirectly.
  • Find the smallest element.
  • Swap it with the first element.
  • What if the first element is the smallest element?
  • You’ll try to assign [0] to [0] ! Self-assignment!

Not very DRY

  • new float (*rhs.data) appears twice— WET !

The copy ctor calls operator= ; as complex objects often do. Initialize data = nullptr so the initial delete data is ok.

Learn C++

21.12 — Overloading the assignment operator

The copy assignment operator (operator=) is used to copy values from one object to another already existing object .

Related content

As of C++11, C++ also supports “Move assignment”. We discuss move assignment in lesson 22.3 -- Move constructors and move assignment .

Copy assignment vs Copy constructor

The purpose of the copy constructor and the copy assignment operator are almost equivalent -- both copy one object to another. However, the copy constructor initializes new objects, whereas the assignment operator replaces the contents of existing objects.

The difference between the copy constructor and the copy assignment operator causes a lot of confusion for new programmers, but it’s really not all that difficult. Summarizing:

  • If a new object has to be created before the copying can occur, the copy constructor is used (note: this includes passing or returning objects by value).
  • If a new object does not have to be created before the copying can occur, the assignment operator is used.

Overloading the assignment operator

Overloading the copy assignment operator (operator=) is fairly straightforward, with one specific caveat that we’ll get to. The copy assignment operator must be overloaded as a member function.

This prints:

This should all be pretty straightforward by now. Our overloaded operator= returns *this, so that we can chain multiple assignments together:

Issues due to self-assignment

Here’s where things start to get a little more interesting. C++ allows self-assignment:

This will call f1.operator=(f1), and under the simplistic implementation above, all of the members will be assigned to themselves. In this particular example, the self-assignment causes each member to be assigned to itself, which has no overall impact, other than wasting time. In most cases, a self-assignment doesn’t need to do anything at all!

However, in cases where an assignment operator needs to dynamically assign memory, self-assignment can actually be dangerous:

First, run the program as it is. You’ll see that the program prints “Alex” as it should.

Now run the following program:

You’ll probably get garbage output. What happened?

Consider what happens in the overloaded operator= when the implicit object AND the passed in parameter (str) are both variable alex. In this case, m_data is the same as str.m_data. The first thing that happens is that the function checks to see if the implicit object already has a string. If so, it needs to delete it, so we don’t end up with a memory leak. In this case, m_data is allocated, so the function deletes m_data. But because str is the same as *this, the string that we wanted to copy has been deleted and m_data (and str.m_data) are dangling.

Later on, we allocate new memory to m_data (and str.m_data). So when we subsequently copy the data from str.m_data into m_data, we’re copying garbage, because str.m_data was never initialized.

Detecting and handling self-assignment

Fortunately, we can detect when self-assignment occurs. Here’s an updated implementation of our overloaded operator= for the MyString class:

By checking if the address of our implicit object is the same as the address of the object being passed in as a parameter, we can have our assignment operator just return immediately without doing any other work.

Because this is just a pointer comparison, it should be fast, and does not require operator== to be overloaded.

When not to handle self-assignment

Typically the self-assignment check is skipped for copy constructors. Because the object being copy constructed is newly created, the only case where the newly created object can be equal to the object being copied is when you try to initialize a newly defined object with itself:

In such cases, your compiler should warn you that c is an uninitialized variable.

Second, the self-assignment check may be omitted in classes that can naturally handle self-assignment. Consider this Fraction class assignment operator that has a self-assignment guard:

If the self-assignment guard did not exist, this function would still operate correctly during a self-assignment (because all of the operations done by the function can handle self-assignment properly).

Because self-assignment is a rare event, some prominent C++ gurus recommend omitting the self-assignment guard even in classes that would benefit from it. We do not recommend this, as we believe it’s a better practice to code defensively and then selectively optimize later.

The copy and swap idiom

A better way to handle self-assignment issues is via what’s called the copy and swap idiom. There’s a great writeup of how this idiom works on Stack Overflow .

The implicit copy assignment operator

Unlike other operators, the compiler will provide an implicit public copy assignment operator for your class if you do not provide a user-defined one. This assignment operator does memberwise assignment (which is essentially the same as the memberwise initialization that default copy constructors do).

Just like other constructors and operators, you can prevent assignments from being made by making your copy assignment operator private or using the delete keyword:

Note that if your class has const members, the compiler will instead define the implicit operator= as deleted. This is because const members can’t be assigned, so the compiler will assume your class should not be assignable.

If you want a class with const members to be assignable (for all members that aren’t const), you will need to explicitly overload operator= and manually assign each non-const member.

guest

C++ Tutorial Operator Overloading II self assignment - 2020

cplusplus_icon.png

Why do we need to protect against the self assignment when we do overloading assignment operator?

But before we dig into the reason why, who would do that kind of silly self assignment?

Anything can happen. When we write a code, we're not supposed to do make any assumption. So, we need to guard against it.

Here is the code without any protection.

The code shows a typical overloading assignment overloading. What could be the flaws in the code?

What could happen if *this and rhs is the same Window instance?

If that's the case, the following line is the problem:

We're deleting rhs.sb since *this and rhs are the same object. After deleting the sb , we're trying to access already deleted object of rhs :

We do not want to that happen. The immediate solution is this:

Still there is a problem.

What if an exception is thrown in the copy constructor after we deleted sb . Then, we're end up having a pointer which is pointing to nothing. So, we need a better code:

In this way, the Window object can still holding the ScrollBar even in when there is a thrown exception.

Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

Sponsor Open Source development activities and free contents for everyone.

C++ Tutorials

  • Create Account

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,305 software developers and data experts.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use .

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.

cppreference.com

Assignment operators.

Assignment operators modify the value of the object.

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

[ edit ] Example

Possible output:

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

[ edit ] See also

Operator precedence

Operator overloading

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 25 January 2024, at 22:41.
  • This page has been accessed 410,142 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Watch CBS News

Target is pulling back on self-checkout, limiting service to people with 10 items or fewer

By Megan Cerullo

Edited By Aimee Picchi

Updated on: March 15, 2024 / 3:30 PM EDT / CBS News

Target is pulling back on what's become a ubiquitous and often speedier way for customers to pay for their purchases in stores. 

The retailer on Thursday said it's making changes to a key part of the buying process — the checkout line. Customers who choose self-checkout will be limited to 10 items, Target said. Otherwise, they'll have to purchase their items via a human cashier before leaving stores. 

Target's "Express Self-Checkout" lanes will hit stores on Sunday at most of its 2,000 locations. The change comes after the company piloted the program at 200 stores last fall, with the company noting that self-checkout was twice as fast at those locations.

Target and other retailers invested heavily in self-checkout options during the pandemic to limit human interaction and mitigate the spread of the virus as well as to save on labor costs. However, some studies have found that self-checkout enables more customer theft. 

For instance, a 2023 LendingTree survey of 2,000 U.S. consumers found that 15% of self-checkout users purposely stole goods. Forty-four percent of self-checkout thieves also said they would do it again. 

Some customers are also souring on self-checkout , with a recent study from Drexel University finding that shoppers feel more loyal to a store and are more likely to revisit if they check out with a human cashier. And self-checkout could pose a financial risk to customers, with reports of credit card skimmers installed in retailers' self-checkout lanes, such as at  several supermarkets in Massachusetts .

Why is Target limiting self-checkout to 10 items?

Target said its impetus for limiting the number of items at self-checkout counters was to improve the customer experience by speeding up the process. 

The retailer will also open more employee-staffed checkout lanes for customers with more than 10 items to help speed up the checkout process overall. Store managers will designate self-checkout lanes' hours based on foot traffic patterns, Target added. 

Other retailers also appear to have cooled on self-checkout after doubling down on it during the pandemic. 

While Walmart hasn't made any public announcements, some shoppers report on social media that the self-checkout lines at their local stores have been closed. 

A Walmart spokesperson told CBS MoneyWatch that it is normal for some of its stores to "adjust the use of staffed checkouts and self-checkouts" depending on customer numbers and staffing levels. "This process isn't new," the spokesperson said.

During these times of limited access, some stores are designating select self-checkout stations for Walmart+ customers using our Scan and Go service and Spark drivers for quicker access and delivery services. This decision is intended to better manage checkout availability.  

img-6153.jpg

Megan Cerullo is a New York-based reporter for CBS MoneyWatch covering small business, workplace, health care, consumer spending and personal finance topics. She regularly appears on CBS News Streaming to discuss her reporting.

More from CBS News

Dollar Tree is closing 600 Family Dollar stores. Here's where.

United now allows travelers to pool their air miles with others

State Farm won't renew homeowners coverage for 72,000 California dwellings

3 times to buy long-term care insurance (and 3 times not to)

Is Walmart getting rid of self-checkout? No, but it's 'testing' how, when to use DIY process

Many customers like self-checkout lanes at stores, because if they have a few items the process goes faster. but retailers face mounting losses from theft. does that mean self-checkout could go away.

check self assignment c

Are the days numbered for self-checkout lanes at your favorite retailer?

The latest sign that could be the case: Some Walmart stores are limiting the use of self-checkout lanes, reserving some for Walmart+ members and drivers for its Spark delivery service , according to a report from news site Business Insider .

Spark drivers reported how self-checkout lanes, available exclusively for them and Walmart+ members, were showing up at the stores they work out of in recent days, Business Insider reported. At the same time, posts on social media also note how self-checkout is being limited at some Walmart stores.

Self-checkout has been a hot topic on Reddit for several months, with Walmart employees noting how some managers are opting to restrict self-checkout lanes, possibly for losses due to theft or incorrect input on food products.

Similarly, consumers who had gotten used to using self-checkout are now confused when they find most or all of the self-checkout lanes closed and lines waiting for clerks at registers racking up the sales.

"All the checkout lines were closed and I had to wait 40 minutes in a line," one person posted on X , formerly Twitter.

Target Circle: Target launches paid membership program, Circle 360, with free unlimited same-day delivery

A shopper at Target posted a photo on X showing self-checkout lanes closed. "SMH why?" they asked.

Self-checkout shifts at Target, Walmart, Costco

These reports come as other retailers in recent months shifted their self-checkout strategies.

Target told USA TODAY in October it had begun experimenting with self-checkout lanes limited to 10 items or fewer at select locations "in order to reduce wait times and better understand guest preferences," according to spokesperson Brian Harper-Tibaldo.

About the same time, Walmart removed self-checkout  at select stores and some stores began posting clerks at self-checkout lanes to watch for possible checkout errors .

In the summer of 2023, Costco began asking staffers to  crack down on checking membership cards  in self-checkout lines. One reason: an increase in "shrink," from theft or products selling for less than actual prices.

Self-checkout's effect on profit isn't new.

In the 2022 report “Global Study on Self-Checkout,” two-thirds (66%) of the 93 retailers in the survey (29 were from North America) said they thought self-checkout losses were becoming more of a problem in their businesses.

"There is no doubt retailers that have invested heavily in (self-checkout) SCO are now having to develop a range of ways in which to keep the associated losses under control," the report's author Adrian Beck, emeritus professor in the Department of Criminology at the University of Leicester in the U.K., told USA TODAY. "Typically, these are a combination of technologies, guardianship, design and changes to store processes."

Is Walmart getting rid of self-checkout?

Not necessarily. Walmart has not issued a corporatewide directive on self-checkout but lets store managers experiment with what works at their location, Walmart spokesperson Joe Pennington told Business Insider.

"Our managers look for ways to innovate within their stores and pay close attention to customer feedback on where they can better meet their needs," he said in a statement sent to USA TODAY. "Based on several factors including customer and associate feedback, shopping patterns, and business needs, some locations are temporarily testing different checkout staffing options."

Any changes, he told Business Insider, are not meant to drive adoption of Walmart+ memberships ($98 annually), which give customers benefits including free deliveries and shipping, plus mobile scan and go shopping using your smartphone in stores.

USA TODAY has also contacted Target for comment about its self-checkout strategies.

After Walmart removed the self-checkout lanes at those select stores, Pennington told USA TODAY in October, "There are no current plans for self-checkout removals nationwide."

But retailers are rethinking what part self-checkouts play in the retail process. They must balance using costly self-checkout lanes and staffing concerns, along with lost revenue from theft and incorrect sales.

"I personally don’t think self-checkout is going away, but we are seeing some big shifts from grocers in this department," said Supermarket News senior editor Bill Wilson in a column this week .

Among other recent developments he cited: Schnucks has limited self-checkout to 10 items or less and Dollar General planned to cut back on self-checkout in 2024.

"Why? Shrink inventory has been a nasty pest over the past year, and it appears some of that theft is happening when shoppers 'forget' to scan items," Wilson said. "Late last year, Kroger began leaning on AI to ensure that items in the cart make it through the scanner and into the bag."

Do you prefer self-checkout? It may depend on your age

Another issue for retailers to balance: Some shoppers love self-checkout, but others do not.

More than 4 out of 10 consumers (43%) preferred self-checkout when buying groceries, according to a survey of 1,133 U.S. consumers by NCR Voyix , released in January.

But Generation Z and Millennial shoppers, aged 18-44, were more likely to prefer it, while only 40% of those ages 45-60 and 26% of those over 60 did.

“The reality is shoppers want more control over their checkout experience and self-checkout delivers that flexibility," NCR Voyix CEO David Wilkinson said in a statement accompanying the report. "For retailers, self-checkout enhances operational efficiency in a time when many are struggling to retain staff and are combatting unprecedented levels of shrink.”

Contributing: Bailey Schulz .

Follow Mike Snider on X and Threads:  @mikesnider  & mikegsnider .

What's everyone talking about? Sign up for our trending newsletter to get the latest news of the day

IMAGES

  1. Advanced C++: Assignment to Self in Assignment Operator

    check self assignment c

  2. Assignment Operators in C Example

    check self assignment c

  3. Assignment Operators in C++

    check self assignment c

  4. Assignment Operators in C

    check self assignment c

  5. C programming +=

    check self assignment c

  6. How to Write a Check Explained in This Simple Step-by-Step Guide

    check self assignment c

VIDEO

  1. how to check self starter motor bypass#automobile #zeeshanauto

  2. Student information and fees submission project in c#

  3. Working with Assignment operators in C| C Tutorials for Beginners

  4. self start motrcycle check self starting ⚡#shorts #short

  5. Reverse array elements using pointers in C Programming| Practical assignment C Programming Part 8

  6. CSE102 Programming Zero C Assignment Statement

COMMENTS

  1. c++

    Example 2: A copy assignment operator that is written in such a way that it must check for self-assignment is probably not strongly exception-safe either. What does he mean by the term "check for self-assignment"? [INQUIRY] Dave and AndreyT shows us exactly what "check for self-assignment" means. That's good. But the question is not over.

  2. Self assignment check in assignment operator

    In C++, assignment operator should be overloaded with self assignment check. For example, consider the following class Array and overloaded assignment operator function without self assignment check. If we have an object say a1 of type Array and if we have a line like a1 = a1 somewhere, the program results in unpredictable behavior because ...

  3. c++

    I have always seen the recommendation that the check is done explicitly. You've been looking in the wrong places, see e.g. C++ Coding Standards by Sutter & Alexandrescu. Self-assignment is exceedingly rare in most programs, so an explicit check adds a small cost to every self-assignment even though the check is almost always false.

  4. Assignment Operators

    If self-assignment can be handled without any extra code, don't add any extra code. But do add a comment so others will know that your assignment operator gracefully handles self-assignment: Example 1a: Fred& Fred::operator= (const Fred& f) {. // This gracefully handles self assignment. *p_ = *f.p_; return *this;

  5. When should we write our own assignment operator in C++?

    Note the if condition in assignment operator. While overloading assignment operator, we must check for self assignment. Otherwise assigning an object to itself may lead to unexpected results (See this). Self assignment check is not necessary for the above 'Test' class, because 'ptr' always points to one integer and we may reuse the same ...

  6. Copy-and-Swap Idiom in C++

    The self assignment check: Self allocation is done very rarely so the self assignment check is not relevant in most of the scenarios. This just slows down the code. Memory deallocation and allocation: As it can be seen that first the memory is deallocated (leaving the pointer dangling) and then the new chunk of memory is allocated. Now if due ...

  7. The assignment operator

    The steps in writing our own assignment operator are the following: Check for self-assignment. Delete old memory. Allocate new memory. Copy the data. Return *this. Notice the worry about self-assignment, as in "A = A". We need to check for this both to avoid unnecessary work and to avoid problems later when we delete the old memory.

  8. bugprone-unhandled-self-assignment

    By default, this check searches only those classes which have any pointer or C array field to avoid false positives. In case of a pointer or a C array, it's likely that self-copy assignment breaks the object if the copy assignment operator was not written with care. See also: OOP54-CPP. Gracefully handle self-copy assignment

  9. CS253

    Copy the resource from the other object to this object. That is, don't just copy the handle (pointer, file descriptor, etc.). Instead you have to make an actual copy of the resource (copy the memory from new, create a new temporary file and copy the contents, etc.).. Of course, this is a copy constructor, not an assignment operator, so there was no previous value.

  10. 21.12

    When not to handle self-assignment. Typically the self-assignment check is skipped for copy constructors. Because the object being copy constructed is newly created, the only case where the newly created object can be equal to the object being copied is when you try to initialize a newly defined object with itself: someClass c { c };

  11. c++

    The copy-and-swap idiom is self-assignment-safe. You don't have to check; in fact, the check is only an optimization in the rare cases where self-assignment actually happens. Otherwise, it's one more branch that could be mispredicted. Efficiency.

  12. What is the proper way to self assignment check in constructor?

    Adding the explicit check before the copy-and-swap would save unnecessary work in the case of self assignment. However, it makes every assignment that isn't a self assignment very slightly slower. Since self assignment is usually rare, I argue that you are better off using copy-and-swap without the explicit check.

  13. Advanced C++: Assignment to Self in Assignment Operator

    Assignment operator is frequently being overloaded. Self-assignment is one thing you need to be careful with when you overload an assignment operator.Notes c...

  14. OOP54-CPP. Gracefully handle self-copy assignment

    User-provided copy operators must properly handle self-copy assignment. The postconditions required for copy assignment are specified by the C++ Standard, [utility.arg.requirements], Table 23 [ ISO/IEC 14882-2014 ], which states that for x = y, the value of y is unchanged. When &x == &y, this postcondition translates into the values of both x ...

  15. C++ Tutorial: Operator Overloading II

    What could happen if *this and rhs is the same Window instance?. If that's the case, the following line is the problem: delete sb; We're deleting rhs.sb since *this and rhs are the same object. After deleting the sb, we're trying to access already deleted object of rhs:. sb = new ScrollBar(*rhs.sb);

  16. Assignment operator self-assignment check

    The self-assignment check detects object identity, which C++ specifies as an. object's addresses. The degenerate situation of copying a value into an object which already had. that value is less important. Just let it happen; don't always waste CPU.

  17. Check for self-assignment with operator=:

    Check for self-assignment with operator=: A common mistake when implementing an assignment is to forget to check for self-references (the this pointer being the same as the argument being assigned). Clients will not normally do this intentionally, but it can happen accidentally, and with aliasing you cannot always tell when it's going to happen.

  18. Assignment operators

    for assignments to class type objects, the right operand could be an initializer list only when the assignment is defined by a user-defined assignment operator. removed user-defined assignment constraint. CWG 1538. C++11. E1 ={E2} was equivalent to E1 = T(E2) ( T is the type of E1 ), this introduced a C-style cast. it is equivalent to E1 = T{E2}

  19. c++

    For either type of direct assignment, the standard isn't to check for self-assignment, but to make sure a self-assignment doesn't cause a crash-and-burn. Generally, no one explicitly does x = x or y = std::move(y) calls, but aliasing, especially through multiple functions, may lead a = b or c = std::move(d) into being self-assignments.

  20. Target is pulling back on self-checkout, limiting service to people

    Target launches new self-checkout policy limiting purchases to 10 items 00:34. Target is pulling back on what's become a ubiquitous and often speedier way for customers to pay for their purchases ...

  21. Walmart: Testing self-checkout in stores, not getting rid of it

    In the 2022 report "Global Study on Self-Checkout," two-thirds (66%) of the 93 retailers in the survey (29 were from North America) said they thought self-checkout losses were becoming more of ...

  22. c++

    w = std::move(w); std::cout << w.size() << std::endl; Of course, the standard says that the move-assignment operator leaves the operand in an unspecified state. For example if the code were x = std::move (w); then we would expect w.size () to be zero. However, is there a specified ordering or other clause that covers the self-move case? Is it ...