Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use string assignment and compund assignment?

Tags:

c++

string

If I have:

#include <string>

std::string myString = "Hello";

then do either:

myString = "Hello World";

or

myString+= " World";

Am I at risk of writing over some other memory?
Do I have to use string functions to add or change the size of the string?

like image 405
Tez Avatar asked Apr 11 '13 08:04

Tez


People also ask

What is the difference between assignment operator and compound assignment operator?

There are two kinds of assignment operations: simple assignment, in which the value of the second operand is stored in the object specified by the first operand. compound assignment, in which an arithmetic, shift, or bitwise operation is performed before storing the result.

How do compound assignment statements compare to regular assignment statements?

The assignment statement stores a value in a variable. Compound assignment combines assignment with another operator.

What are the compound assignment operators and how are they useful?

The compound assignment operators consist of a binary operator and the simple assignment operator. They perform the operation of the binary operator on both operands and store the result of that operation into the left operand, which must be a modifiable lvalue.


1 Answers

With std::string, that's completely fine as std::string manages its own memory.

With c-style strings using char*, you need to manage your own memory.

like image 52
Pubby Avatar answered Oct 06 '22 00:10

Pubby